JavaScript Float32Array check if transferable object is neutered

1.2k views Asked by At

I'm using transferable objects between my main thread and physics worker. The Float32Array is being passed back and forth and it works quite nice. How do I check if Float32Array is neutered?

For example this is an array:

this.transferableArray = new Float32Array();

Send as transferable object

worker.postMessage(this.transferableArray, [this.transferableArray.buffer]);

Currently in my code I check if it's neutered like that:

if (!transferableArray.length) {
    return false;
}

Is this the right way of doing it or is there some method which specifically tells if the array is neutered? This is a game so every millisecond gain matters.

2

There are 2 answers

1
Kaiido On

Checking for 0 .byteLength should be enough in 99% of the cases.

If you really need to handle the remaining 1%, you can try to call its slice() method, which would throw if the ArrayBuffer is detached.

function isDetached( arrayBuffer ) {
  if( arrayBuffer.byteLength > 0 ) { return false; }
  try {
    arrayBuffer.slice( 0, 0 );
    return false;
  }
  catch( e ) {
    return true;
  }
}

const arr = new Float32Array( 0 );

console.log( 'before transfer:', isDetached( arr.buffer ) );

// transfer
const channel = new MessageChannel();
channel.port1.postMessage( arr, [ arr.buffer ] );

console.log( 'after transfer:', isDetached( arr.buffer ) );

0
Pawel On

after sending an array it's becoming useless so now I'm just unsetting the property after sending it.

worker.postMessage(this.transferableArray, [this.transferableArray.buffer]);
this.transferableArray = undefined;

now, at any point in time it can be easily checked if it came back by checking

if(!this.transferableArray) {
    return;
}