I have some processing which isn't necessarily cpu-intensive, but lots of temporary objects are created which results in unsavory Garbage Collector hiccups during animation etc.
Will offloading that temp-object creation process to web workers help alleviate that? In other words - will the GC hiccups be isolated to the web worker thread and not affect my main thread, or is GC something that will affect both threads?
How many web workers can run concurrently JavaScript? A web worker is a JavaScript program running on a different thread, in parallel with main thread. The browser creates one thread per tab. The main thread can spawn an unlimited number of web workers, until the user's system resources are fully consumed.
There are two kinds of workers; dedicated workers, and shared workers. Dedicated workers, once created, and are linked to their creator; but message ports can be used to communicate from a dedicated worker to multiple other browsing contexts or workers.
The garbage collector considers unreachable objects garbage and releases the memory allocated for them. During a collection, the garbage collector examines the managed heap, looking for the blocks of address space occupied by unreachable objects.
The SharedWorker interface represents a specific kind of worker that can be accessed from several browsing contexts, such as several windows, iframes or even workers. They implement an interface different than dedicated workers and have a different global scope, SharedWorkerGlobalScope .
The ECMAScript specification does not specify any form memory management, garbage collection is only referred to in non-normative parts.
Similarly the web worker spec does not say much about garbage collection except wrt. to how long some objects must live.
So this is implementation-specific behavior. Even if implementations implement a per-worker GC and avoid shared overhead in the general case they might still trigger a global collection of all workers due to memory pressure, especially on memory-constrained systems.
That said, it is more likely that you will achieve some GC isolation with workers than without. But you have to take care to avoid messaging overhead between workers and the main thread, since serializing messages (for the structured clone algorithm) can produce additional garbage. Using transferables or shared memory buffers can avoid this.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With