gpt4 book ai didi

javascript - WebWorker - 传输包含对象的数组

转载 作者:行者123 更新时间:2023-11-28 09:06:53 28 4
gpt4 key购买 nike

我有一个数组,需要将其从 WebWorker 传输回主线程。据我所知,只有 ArrayBuffers 和 TypedArrays 是可传输的,其他任何内容都是复制而不是传输的。

我遇到的问题是数组包含对象,所以我不确定如何传输它们(由于尺寸巨大,这是需要的)。

例如假设我有:

function something() {
this.x = 1;
this.y = 2;
this.z = 3;
}

var array = [];
for (var x = 0; x < 6; x++) {
array[x] = new something();
}

有没有办法可以将数组转换为 ArrayBuffer,传输它然后再转换回来?

感谢您的帮助!

最佳答案

考虑在创建对象时为数组(对象?)的每个元素进行发布。然后将其放入 onmessage 处理程序中的数组中。

function something() {
this.x = 1;
this.y = 2;
this.z = 3;
}

var array = [];
for (var x = 0; x < 6; x++) {
postMessage(new something());
}

这应该适用于简单的对象,例如示例中的对象,但您必须测试边界。

Data passed between the main page and workers are copied, not shared. Objects are serialized as they're handed to the worker, and subsequently, de-serialized on the other end. The page and worker do not share the same instance, so the end result is that a duplicate is created on each end. Most browsers implement this feature as structured cloning.

MDN: Passing Data

关于javascript - WebWorker - 传输包含对象的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16925624/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com