Isaac King
Isaac King

Reputation: 378

Is there any significant overhead to having an idle web worker?

I'm wondering what the use of worker.terminate() is. If I'm not using a web worker anymore, why kill it rather than leave it alive for the next time I need one? (Given how much time it takes to create new web workers (~200ms in my recent tests), this can save a lot of time.) Or even if I never need to use it again, what's the downside of leaving it alive?

I assume they each have their own event loop, so there will be a tiny amount of overhead from that, but as long as they're not doing any calculations during their idle time, I can't imagine that would cause much lag on its own.

I performed some brief tests and found that large enough numbers of web workers (>2500) will crash the tab, but as long as I stay below that limit, they don't seem to slow the page down after the initial freeze while they're all being initialized. As far as I could tell, having 2000 workers idling in the background didn't cause CPU intensive tasks to take any longer, nor interfere with any other aspect of the web page or browser.

So my specific question is, is there ever a good performance-based reason to call worker.terminate()? If so, what?

Upvotes: 1

Views: 929

Answers (1)

Kaiido
Kaiido

Reputation: 137084

CPU wise that should be almost transparent to the main thread, they do indeed run their own event-loop but if no new task is performed that should not have any visible impact. Note that if the worker becomes orphan, the browser will even kill it itself.

However, memory wise they can have a significant impact. So if your worker needs to perform an heavy operation and to allocate a lot of persistent objects, it may be a good idea to kill it once the job is done.

But yes, the best is to have a single worker that can do multiple tasks during the page's life-span, or even better, a pool of such workers. But it's currently very tedious to implement this1, and for scripts like libraries they sometimes don't have much choice but to create their own single-use workers. In such a case it's preferable to kill the worker after use.

1. This thread leaves some hope that we may have something easier to use in the future.

Upvotes: 1

Related Questions