0

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.

Pawel
  • 16,093
  • 5
  • 70
  • 73

2 Answers2

1

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;
}
Pawel
  • 16,093
  • 5
  • 70
  • 73
1

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 ) );
Community
  • 1
  • 1
Kaiido
  • 123,334
  • 13
  • 219
  • 285
  • I switched to SharedArrayBuffer since the post but this seems like a valid solution. Actually outside of WebKit it's still the old method because of meltdown vulnerability issue – Pawel Apr 21 '20 at 10:04