Javascript Worker.postmessage Shrinks Empty Array
Solution 1:
Data is copied to workers via the structured cloning algorithm, so your worker is not getting the exact array you created, that would be a thread-unsafe operation as arrays are a reference type. This is a case where the MDN docs are incomplete, generally speaking with a few exceptions the structured cloning algoritm is equivalent to JSON.parse(JSON.stringify(x))
but this is an exception as JSON.parse(JSON.stringify(new Array(4)))
yields [null, null, null, null]
at least in chrome and ff.
The weird behavior here is probably in part because there really isn't any point to creating arrays with empty slots like that, there aren't even any indicies, e.g. new Array(4).forEach(i => console.log('foo'));
doesn't do anything. So the structured cloning algorithm generates an empty array.
Note that the structured cloning algorithm is not part of the JavaScript specification, it is rather part of the HTML 5 spec and as far as I can tell doesn't give a lot of details, so I'm not entirely sure how it works, but seems to be focused on things like fileData and Blobs. Note that cloning an arraybuffer is part of the Ecmascript spec. All of that makes some sense, workers have a huge performance penalty for the communication overhead (which is why shared-memory constructs have been proposed) in no small part due to that same algorithm. So the computation you want to do in them has to be intensive enough to outweigh the startup and communication penalties. So it makes sense that the communication channel is more focused on those low-level (essentially binary in the blob case) data constructs.
Post a Comment for "Javascript Worker.postmessage Shrinks Empty Array"