[英]Is there a way to pass an array of objects to a web worker as a transferable object?
I'm working on a CPU and memory intensive project for which some of the processing is sent to a web worker in order to not hang the browser while its number crunching. 我正在处理一个CPU和内存密集型项目,该项目的某些处理已发送给Web Worker,以便在处理数字时不会挂起浏览器。 The problem I am facing is that I need to send to the web worker instance a few multidimensional arrays, but upon profiling the app I realized it was cloning the arrays, so I'l trying to see if I pass them as transferable objects.
我面临的问题是我需要向Web Worker实例发送一些多维数组,但是在对应用程序进行性能分析时,我意识到它正在克隆数组,因此,我将尝试查看是否将它们作为可传递对象传递。
For simplicity assume that the arrays I'm trying to pass are: 为了简单起见,假设我要传递的数组是:
var myArray1 = [{a: 0, b: "0"}, {a: 1, b: "0"}]; var myArray1 = [{a:0,b:“ 0”},{a:1,b:“ 0”}];
var myArray2 = [{c: 0, d: "0"}, {c: 1, d: "0"}]; var myArray2 = [{c:0,d:“ 0”},{c:1,d:“ 0”}]];
Is there a way to pass these as transferable objects to a web worker instance? 有没有办法将这些作为可传递对象传递给Web Worker实例?
Not directly but ArrayBuffers
and SharedArrayBuffers
can be transferred to web workers and if your data is as uniform as in your example then it would be possible to store that data in an array buffer rather than an array of objects. 可以不直接将
ArrayBuffers
和SharedArrayBuffers
传递给Web Worker,并且如果您的数据与示例中的相同,则可以将数据存储在数组缓冲区而不是对象数组中。
Instead of 代替
const arr = [{ a: 0, b: '0' }];
you might store the data as 您可以将数据存储为
const ab = new ArrayBuffer(2 * 4);
const dv = new DataView(ab);
dv.setFloat32(0, 0);
dv.setUint32(4, '0'.charCodeAt(0));
And then read it back using a data view in the worker, as well. 然后,也使用worker中的数据视图将其读回。 This will let you transfer the data to the worker using a transferable item.
这样您就可以使用可转让项目将数据转让给工人。 Of course this all depends on your data and how it's structured.
当然,这一切都取决于您的数据及其结构。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.