I'm trying to see the performance difference between for and reduce over numeric array and I can see that always the second function that I'm measuring (whatever is, for or reduce) is faster than the first. I'm guessing that it is something related to data caching or threadpool size using node. This is the code:
process.env.UV_THREADPOOL_SIZE = 1;
let array = [
1,
23,
4,
5,
6,
7,
8,
7,
65,
4,
3,
23,
43,
2,
23,
32,
23,
23,
234,
243,
423,
432,
43,
23,
2,
23,
2,
23,
];
let sum = 0;
console.time('reduce');
sum = array.reduce((s, p) => (s += p), 0);
console.timeEnd('reduce');
sum = 0;
console.time('for');
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.timeEnd('for');
And this code shows different results:
process.env.UV_THREADPOOL_SIZE = 1;
let array = [
1,
23,
4,
5,
6,
7,
8,
7,
65,
4,
3,
23,
43,
2,
23,
32,
23,
23,
234,
243,
423,
432,
43,
23,
2,
23,
2,
23,
];
let sum = 0;
console.time('for');
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.timeEnd('for');
sum = 0;
console.time('reduce');
sum = array.reduce((s, p) => (s += p), 0);
console.timeEnd('reduce');
I mean, if you reverse the order of execution, the measured results are different.
To do the test I'm using node v11.11.0
Any idea about it?
EDIT: I'm not looking for explanation why reduce is faster than for or something like that. I want to know why nodejs produce that results in this sequence of operations.