EN
JavaScript - what is the fastest way to sum array elements?
1
answers
0
points
What is the fastest way to sum array elements in JavaScript?
I've heard you can sum arrays with reduce()
method but I was using a simple for loop so far, e.g:
// ONLINE-RUNNER:browser;
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var sum = 0;
for (var i = 0; i < array.length; i++) {
sum = sum + array[i];
}
console.log(sum); // 55
1 answer
0
points
When it comes to performance, the for loop is more efficient than reduce()
method.
However, if "the fastest" method means a one-liner for you, use the reduce()
.
Practical examples
1. Using for loop (the most efficient)
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let result = 0;
for (let i = 0; i < array.length; ++i) {
result += array[i];
}
console.log(result); // 55
2. Using reduce()
method (one-liner)
// ONLINE-RUNNER:browser;
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const result = array.reduce((previous, current) => previous + current, 0);
console.log(result); // 55
Performance test
In this section, I've compared two methods of summation:
sum1()
- usesreduce()
method,sum2()
- usesfor
loop.
// ONLINE-RUNNER:browser;
const test = (repeats, description, func) => {
const t1 = Date.now();
for (let i = 0; i < repeats; ++i) {
func();
}
const t2 = Date.now();
const dt = t2 - t1;
console.log(`${description}: totoal time is ${dt} ms`);
};
// Tested algorithms:
const sum1 = (array) => {
return array.reduce((previous, current) => previous + current, 0);
};
const sum2 = (array) => {
let count = 0;
for (let i = 0; i < array.length; ++i) {
count += array[i];
}
return count;
};
// Input array:
const array1 = [
1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4,
5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3,
4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2,
3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1,
2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5,
];
// Performance tests:
const repeats = 10000; // set number of repeats depending on cases complexity
test(repeats, 'Using reduce()', () => sum1(array1));
test(repeats, 'Using for loop', () => sum2(array1));
See also
References
0 comments
Add comment