Is there a way to create a TypedArray from an ArrayBuffer without using new keyword in Javascript?

169 Views Asked by At

I am using transferables to communicate between the main thread and the worker. I realized the communcation creates GC activity because after receiving the buffer, I'm converting the buffer to a typed array using the new keyword:

var ary = new Float32Array(buffer);

Is there a way to re-use a TypedArray or getting a view of a buffer without creating GC activity?

1

There are 1 best solutions below

0
On BEST ANSWER

I don't think there is, no. ArrayBuffer is pretty much a black box without a typed array or DataView to look into it, and you can't change the buffer on an existing typed array or DataView.

On platforms that support it, you can create a SharedArrayBuffer that both the main and worker thread have access to, which wouldn't have the GC problem since each side would reuse its wrapper array. Just make sure you gatepost access to it via postMessage or Atomics (more about that in this question's answer).

But sadly, most browsers disabled SharedArrayBuffer in response to Spectre, and the last I checked only Chrome has re-enabled it (on platforms where its site isolation feature is enabled).