Your last snippet only defers the code execution to the next iteration of the event loop. If it's synchronous, Since it's "blocking" anyways (no IO or network requests), why not just `let result = collection.map(expensiveFunction)` ?
new Promise(resolve => {
const out = [];
const iterator = collection[Symbol.iterator]();
function next() {
const item = iterator.next();
if (item) {
setTimeout(() => {
out.push(expensiveFunction(item.value));
next();
});
} else {
resolve(out);
}
}
next();
});
JavaScript’s threading model is rather hostile to expensive CPU-bound functions. Workers are just too hard to use unless you go all in with that architecture. I love being able to work with things like Rayon in Rust.Typed arrays can be zero-copy transferred to a worker extremely quickly, modified, then transferred back if needed.
No costly copying or cloning needed. But it won't work with just objects, just typed arrays.