EN
JavaScript - for, for-each and forEach performance test
9
points
In this article, I would like to show results from simple performance tests for different types of for loop made on int array in JavaScript (V8 in Google Chrome v92).
Tests show what loop type is faster in different cases.
Below test conclusions:
forloop is fastest in most cases,- in some cases
forEachwas faster.- for some arrays sizes
forloop is always faster, and for otherforEachmethod.
Used JavaScript Engine: V8 in Google Chrome v92
Used OS: Windows 10 x64
Used PC:
- Ryzen 9 5900x
- DRR 4 (2x 32GB)
- Samsung SSD M.2 970 EVO (1TB)
- GeForce GTX 970 (4GB RAM)
Total times needed to iterate over the array:
for type | for time | Array size |
for loop | 0.003 ms | 10 |
for-each | 0.005 ms |
10 |
forEach() | 0.049 ms | 10 |
for loop | 0.066 ms | 100 |
for-each | 0.006 ms |
100 |
forEach() | 0.03 ms | 100 |
for loop | 0.016 ms | 1_000 |
for-each | 0.022 ms |
1_000 |
forEach() | 0.051 ms | 1_000 |
for loop | 0.13 ms | 10_000 |
for-each | 0.308 ms | 10_000 |
forEach() | 0.119 ms | 10_000 |
for loop | 2.1525 ms | 100_000 |
for-each | 3.585 ms | 100_000 |
forEach() | 1.13 ms | 100_000 |
for loop | 3.333 ms | 1_000_000 |
for-each | 11.407 ms | 1_000_000 |
forEach() | 8.87 ms | 1_000_000 |
for loop | 12.6 ms | 10_000_000 |
for-each | 91.697 ms | 10_000_000 |
forEach() | 108.588 ms | 10_000_000 |
for loop | 86.882 ms | 100_000_000 |
for-each | 753.454 ms | 100_000_000 |
forEach() | 1072.257 ms | 100_000_000 |
Used source code:
const test = (description, action) => {
console.time(description);
action();
console.timeEnd(description);
};
// Usage example:
const array = Array(1000); // change it to desired size
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
test('for loop', () => {
let sum = 0;
for (let i = 0; i < array.length; i++) {
sum += array[i];
}
console.log(`sum: ${sum}`);
});
test('for-each loop', () => {
let sum = 0;
for (const value of array) {
sum += value;
}
console.log(`sum: ${sum}`);
});
test('forEach() method', () => {
let sum = 0;
array.forEach(value => sum += value);
console.log(`sum: ${sum}`);
});