The optimized fix

Why not combine the good parts of atomics and the good parts of the speed of local variables sitting in the CPU register? Here we are:

// worker.jslet sharedMem;addEventListener('message', ({data}) => {  //console.log(data);    if(data.message == 'sab') {        sharedMem = data.memory;        console.log('Memory ready');    }    if(data.cmd == 'start') {      console.log('Iterations ready');        startCounting(data.iterations);    }});function startCounting(limit) {    const arr = new Uint32Array(sharedMem);    let count = 0;    for(let i=0;i<limit;i++) {        count += 1;    }    Atomics.add(arr, 0, count);    postMessage('done')}

Here, from our last implementation, we took Atomics.add out of the loop to avoid calling it a billion times. Instead, we performed the work assigned to ...

Get Learn ECMAScript - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.