Dedicated Workers

Workers are useful for allowing your code to perform CPU intensive calculations without blocking or freezing the main thread from executing other JavaScript codes.

A dedicated worker is only accessible by the script that called it.

Your Hardware Concurrency

2

In this example, we are going to apply a Sobel filter to the following 6K (6000 * 3000) image. A Sobel filter is used in image processing and computer vision, where an image is generated with the edges emphasized of the input image. Firstly, we will execute the serial code - then we are going to perform the same operation using multiple web workers set by an input. When running the serial version, try interacting with the DOM!

Serial Conversion

Initial Image

Sobel Filtered Image

Results:

After running the serial conversion, it can be well observed that execution is creating 'lag' and blocking the master thread. The image below displays the performance developer tool in the browser. Each user will get their own results; you can see the DOM clicking event where our browser was in the pointer phase.

To fix this, we want to run the filtering algorithm on a separate thread(s) and leave the master thread so the user can continue to interact with the website. We will achieve this by utilizing JavaScript's Web Workers.

Parallel Conversion

Initial Image

Sobel Filtered Image

Results:

The parallel version of Sobel Filtered running on multiple web workers is much faster than the serial version. We define the number of threads to web workers to create and break our image into horizontal chunks (height/# of workers). We then generate the worker, and wait for all of the workers to complete before patching everything together. Below you will be able to compare the execution time per processor. You can change the # of processors used using the slider.

Execution time per processor