JavaScript:Web Worker 和类型化数组
我有一个 Web Worker(从 new Worker()
开始)进行一些处理,并应该返回一个 Float32Array
。
然而,在工作人员 postMessage()
获取数据之后,它会经过序列化和反序列化为 JSON,而我在接收消息时最终得到的是一个普通的 javascript Array
(具有原始类型化数组具有的所有属性)
一个简单的解决方法是从 javascript 数组重新创建类型化数组,但这很浪费并且占用时间和内存。
有更好的方法吗?某种方式告诉 JSON 反序列化实例化 Float32Array 而不是 javascript 数组?或者以其他方式传输二进制数据的方法?
I have a web worker (started with new Worker()
) that does some processing and is supposed to return a Float32Array
.
It seems however that after the worker 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 otherwise transfer the binary data?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
所有支持worker的浏览器(IE10除外)都支持所谓的可传输对象,这意味着如果您有一个数组缓冲区(即采用类型化数组的.buffer属性),您可以作为postMessage的第二个参数包含数组缓冲区列表您想将所有权转让回来。这比复制要快得多。
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.
更新:目前这似乎是 Chrome 的一个错误:
http:// code.google.com/p/chromium/issues/detail?id=73313
类型化数组在 Firefox 4 中保留。
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.