Search code examples
javascriptperformanceweb-worker

Is a Web Worker faster than running a script?


I was tasked with creating a dedicated webworker instance on each page to handle sending a server request on a given interval regardless of what page the user is on. Since this must work for any browser, a shared webworker was not an option (hence why it must be loaded for each page).

I created a script, thinking that I had been creating a worker, but I was informed recently that workers were not actually being created, though the script was doing the intended function of the webworker.

The basic function of the webworker was this:

onPageLoad {

    function sendHeartbeat() {
        sendRequest(URL);
    }

    function startHeartbeat() {
        if(timeToSendHeartbeat) {
             sendHeartbeat();
        } else {
             setInterval(timeRemaining, sendHeartbeat());
        }
    }
}

This got me to thinking about whether or not using a webworker was even the best choice. Is there some inherent advantage to using a webworker that I am missing? Is using a webworker no more efficient than attaching a script to each page and running it as is? Or is this application just not suited for a webworker to begin with?


Solution

  • WebWorkers just run scripts, so they won't be faster than other methods. They shine by running in a different thread and not blocking the UI or any other code that wants to run in the main thread.

    The real deciding factor is whether the code to be worker-ized runs for long enough to cause problems with the rest of the application. If you have intervals that need to fire on time or a very long-running math operation, you may want to start up a worker and let it go for a bit, then grab the results at the end.

    So far as the main thread is concerned, workers and API calls are not entirely different in principal. You're sending someone else off to do the work and collecting results when they finish. Whether it happens on a server or another thread is less important, the part to focus on is the main thread is not doing the work.