1)As we know, there's no side-effect with map() and reduce(). Nowadays, we also have muti-core on cell phone. So is it more efficient to use them?
2)On the other hand, there's only 1 thread for js to execute on most of the browsers. Therefor map() and reduce() are prepared for server-side scripting?
I just tested this today, using map and reduce over floating point numbers, with the latest node.js version, and the answer is that map and reduce was two orders of magnitude slower than an regular for loop.
var r = array.map(x => x*x).reduce( (total,num) => total+num,0);
~11,000ms
var r = 0.0;
array.forEach( (x,i,a) => r += x*x )
~300ms
var r = 0.0;
for (var j = 0; j < array.length;j++){
var x = array[j];
r += x*x;
}
~35ms
EDIT: One should note that this difference is much less in Firefox, and may be much less in future version of Node / Chrome as well.
1)
there's no side-effect with map() and reduce()
Well. You very well can implement map and reduce callbacks having side effects. Nothing prevents it and in the current state of JavaScript it's not even considered as bad practice.
2)
there's only 1 thread for js to execute on most of the browsers
There's only one thread in all today's JS engines, even when they run server-side (in fact there can be more but in isolation, not accessing the same array).
So the fact there is no side effect wouldn't make array modifications parallelisable at all. No JS engine can do otherwise than call the callback sequentially on standard arrays.
Note : as pointed by zirak, there's this not standard Mozilla ParallelArray thing which could help making parallel execution. I don't know if there's something similar on V8.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With