Multithreading in Node JS | main & worker threads
Once upon a starry night, I was attempting to evaluate what performance improvements happen once we carefully move CPU intensive processes into worker threads.
As a use case I thought about creating a couple of loops which execute synchronously one after the other. And then move one of the loops inside a worker thread; compare their performances.
At my first attempt, I created a simple for loop.
for(var i = 0; i < 1e6; i++){ i = i * 5;}
Ran it twice, and found the time taken using console.time & console.timeEnd. Then moved the first loop inside a worker thread and again found out the time taken for execution.
Get Anirvann Das’s stories in your inbox
Join Medium for free to get updates from this writer.
Unsurprisingly the worker thread example takes more time as the overhead of creating a thread for a simple operation is an overkill. Below are the results.
Changed the code inside for loop by pushing i * 5 into an array.
const arr = [];
for(var i = 0; i < 1e6; i++){ arr.push(i * 5);}
Still worker thread is a overkill!
So I decided to change it and create a HMAC hash which gets pushed into the array.
const arr = [];for(var i = 0; i < 1e6; i++){ let hash = crypto
.createHmac('sha256', secret)
.update(i.toString())
.digest('hex'); arr.push(hash);}
hashing is a CPU intensive operation and here worker thread shows its real power.
I have attached the code gist below.
To run this, one would need the — experimental-worker flag.
node --experimental-worker index.jsWould love to hear your comments on similar experiments.
Next up, am planning to share a comparison experience between node clustering v/s PM2.






