Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass object by reference from/to webworker

Is it possible passing an object from/to webWorker from/to main thread by reference? I have read here information about transferable objects.

Chrome 13 introduced sending ArrayBuffers to/from a Web Worker using an algorithm called structured cloning. This allowed the postMessage() API to accept messages that were not just strings, but complex types like File, Blob, ArrayBuffer, and JSON objects. Structured cloning is also supported in later versions of Firefox.

I just want to pass information, not object with methods. Just something like this (but with a lot of information, a few MB, so that main thread does not have to receive a copy of the object):

var test = {
    some: "data"
}
like image 287
javifm Avatar asked Nov 05 '15 12:11

javifm


1 Answers

Once you have some data in an object (this: {bla:666, color:"red"}) you will have to copy it and there is no way to avoid it. The reason is, that you don't have control over the memory object is stored in, so you can't transfer it. The only memory that can be transferred is memory allocated for transferable objects - typed arrays.

Therefore if you need some data transferred, you must think in advance and use the transferable interface. Also keep in mind that even when object is copied, the transfer speed is very fast.

I wrote a library that converts object to binary data (therefore transferable), but it isn't faster than native transfer, it's way slower actually. The only advantage is that it allows me to transfer unsupported data types (eg. Function).

like image 166
Tomáš Zato - Reinstate Monica Avatar answered Oct 06 '22 17:10

Tomáš Zato - Reinstate Monica