Appendix. Structured Clone Algorithm
The structured clone algorithm is a mechanism that JavaScript engines use when copying objects using certain APIs. Most notably, it’s used when passing data between workers, though other APIs use it as well. With this mechanism, data is serialized and then later deserialized as an object inside another JavaScript realm.
When objects are cloned in this manner, such as from the main thread to a worker thread or from one worker to another, modifying an object on one side will not affect the object on the other side. There are essentially two copies of the data now. The purpose of the structured clone algorithm is to provide a friendlier mechanism for developers than what JSON.stringify
does, while imposing reasonable limitations.
Browsers use the structured clone algorithm when copying data between web workers. Node.js, similarly, uses it when copying data between worker threads. Basically, when you see a .postMessage()
call, data being passed in is cloned in this way. Browsers and Node.js follow the same rules, but they each support additional object instances that can be copied.
As a quick rule of thumb, any data that can be cleanly represented as JSON can be safely cloned in this manner. Sticking to data represented in this manner will certainly lead to very few surprises. That said, the structured clone algorithm supports several other types of data as well.
First off, all of the primitive data types available in JavaScript, with the exception ...
Get Multithreaded Javascript now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.