Languages
[Edit]
EN

JavaScript - for, for-each and forEach performance test

9 points
Created by:
Evania
584

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:

  • for loop is fastest in most cases,
  • in some cases forEach was faster.
  • for some arrays sizes for loop is always faster, and for other forEach method.

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 typefor timeArray size
   
for loop0.003 ms10
for-each0.005 ms

10

forEach()0.049 ms10
   
for loop0.066 ms100
for-each0.006 ms

100

forEach()0.03 ms100
   
for loop0.016 ms1_000
for-each0.022 ms

1_000

forEach()0.051 ms1_000
   
for loop0.13 ms10_000
for-each0.308 ms10_000
forEach()0.119 ms10_000
   
for loop2.1525 ms100_000
for-each3.585 ms100_000
forEach()1.13 ms100_000
   
for loop3.333 ms1_000_000
for-each11.407 ms1_000_000
forEach()8.87 ms1_000_000
   
for loop12.6 ms10_000_000
for-each91.697 ms10_000_000
forEach()108.588 ms10_000_000
   
for loop86.882 ms100_000_000
for-each753.454 ms100_000_000
forEach()1072.257 ms100_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}`);
});

Alternative titles

  1. JavaScript - for performance comparison
  2. JavaScript - for, for-each and forEach efficiency test
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join