Skip to main content

Allocation Zones

Allocation zones determine where buffer memory is allocated and affect performance, IPC capabilities, and garbage collection behavior.

Overview

import com.ditchoom.buffer.AllocationZone

val buffer = PlatformBuffer.allocate(
size = 1024,
zone = AllocationZone.Direct // Choose your zone
)

Zone Types

AllocationZone.Heap

Memory allocated on the JVM heap (or equivalent on other platforms).

val buffer = PlatformBuffer.allocate(1024, AllocationZone.Heap)

Characteristics:

  • Managed by garbage collector
  • May require copying for native I/O operations
  • Good for short-lived, small buffers

Platform behavior:

PlatformImplementation
JVMHeapByteBuffer
AndroidHeapByteBuffer
WASMByteArrayBuffer
OthersByteArrayBuffer

AllocationZone.Direct

Memory allocated outside the JVM heap (off-heap).

val buffer = PlatformBuffer.allocate(1024, AllocationZone.Direct)

Characteristics:

  • Not managed by garbage collector
  • Zero-copy I/O with native code
  • Best for network I/O and file operations
  • Default allocation zone

Platform behavior:

PlatformImplementation
JVMDirectByteBuffer
AndroidDirectByteBuffer
iOS/macOSNSMutableData
JavaScriptInt8Array
WASMLinearBuffer (native WASM memory)
LinuxByteArrayBuffer

Heap vs Direct Memory

AllocationZone.SharedMemory

Memory that can be shared across process boundaries.

val buffer = PlatformBuffer.allocate(1024, AllocationZone.SharedMemory)

Characteristics:

  • Enables zero-copy IPC (Inter-Process Communication)
  • Platform-specific availability
  • Useful for Android services and multi-process apps

Platform behavior:

PlatformImplementation
Android (API 27+)SharedMemory
Android (< API 27)Falls back to DirectByteBuffer
JavaScriptSharedArrayBuffer (requires CORS headers)
WASMLinearBuffer (falls back to Direct)
OthersFalls back to Direct

SharedMemory IPC

Platform-Specific Notes

Android SharedMemory

All JvmBuffers are Parcelable. For zero-copy IPC:

// In your Service or ContentProvider
val buffer = PlatformBuffer.allocate(1024, AllocationZone.SharedMemory)
buffer.writeBytes(data)

// Pass through Binder
parcel.writeParcelable(buffer as Parcelable, 0)

JavaScript SharedArrayBuffer

Requires CORS headers. Add to webpack.config.d/:

if (config.devServer != null) {
config.devServer.headers = {
"Cross-Origin-Opener-Policy": "same-origin",
"Cross-Origin-Embedder-Policy": "require-corp"
}
}

Without proper headers, falls back to regular ArrayBuffer.

Choosing a Zone

Use CaseRecommended Zone
Network I/ODirect
File I/ODirect
Short-lived parsingHeap or pool from Direct
Android IPCSharedMemory
Multi-threaded JSSharedMemory
General purposeDirect (default)