JavaScript: Web Worker and Typed Arrays
I have a web worker (started with new Worker()
) that does some processing and is supposed to return a Float32Array
.
postMessage()
s the data, it goes through serialization and desirialization to JSON and what I end up with when receiving the message is a plain javascript Array
(with all of the properties the original typed array had)
A trivial work around would be to just recreate the typed array from the javascript array but that's wasteful and takes up time and memory.
Is there a better way to do this? Some kind of way to tell the JSON deserialization to instantiate a Float32Array
instead of a javascript array? or a way to othe开发者_开发知识库rwise transfer the binary data?
All browsers that support workers (except IE10) support what's called transferable objects which means that if you have an array buffer (ie take your the .buffer property of your typed array) you can as a second parameter of postMessage include a list of array buffers you want to transfer ownership of back. This is much much faster than copying it.
update: this seems to be a Chrome bug at the moment:
http://code.google.com/p/chromium/issues/detail?id=73313
typed array are preserved in Firefox 4.
精彩评论