Objects that own resources that can be transferred from one context to another, ensuring that the resources are only available in one context at a time.
Following a transfer, the original object
is no longer usable
Transferable objects are commonly used to share resources that can only be safely exposed to a single JavaScript thread at a time.
// Create an 8MB "file" and fill it. 8MB = 1024 * 1024 * 8 B const uInt8Array = new Uint8Array(1024 * 1024 * 8).map((v, i) => i); console.log(uInt8Array.byteLength); // 8388608 // Transfer the underlying buffer to a worker worker.postMessage(uInt8Array, [uInt8Array.buffer]); console.log(uInt8Array.byteLength); // 0
For example, an ArrayBuffer
is a transferable object that owns a block of memory.
When such a buffer is transferred between threads
, the associated memory resource is detached from the original buffer
and attached to the buffer object
created in the new thread.
The buffer object
in the original thread
is no longer usable because it no longer owns a memory resource.
Typed arrays like Int32Array
and Uint8Array
, are serializable
, but NOT transferable
.
However their underlying buffer
is an ArrayBuffer
, which is a transferable object
.
We could have sent uInt8Array.buffer
in the data parameter, but not uInt8Array
in the transfer array.