var arr = [];
for (var i = 0; i<10000; i++) {
arr.push(i);
}
var sum = 0;
for (var j = 0; j < arr.length; j++) {
sum = sum + j;
}
var arr = [];
for (var i = 0; i<10000; i++) {
arr.push(i);
}
var sum = 0;
arr.forEach(function(num) {
sum = sum + num;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for loop | |
for each |
Test name | Executions per second |
---|---|
for loop | 26604.4 Ops/sec |
for each | 10775.4 Ops/sec |
I'll explain the benchmark in detail.
Benchmark Overview
The benchmark compares two approaches for iterating over an array of numbers: traditional for
loops and forEach
method. The goal is to measure which approach is faster.
Options Compared
There are two options compared:
for
loop: This approach uses a manual counter variable (i
) to iterate over the array, with explicit bounds checking.forEach
method: This approach uses the Array.prototype.forEach()
method, which iterates over the array using a callback function.Pros and Cons of Each Approach
for
loop:forEach
method:Library and Purpose
In this benchmark, there is no explicit library mentioned. However, the Array.prototype.forEach()
method is a part of the ECMAScript standard (ES6+) and is widely supported by modern JavaScript engines.
Special JS Feature or Syntax
There are no special JavaScript features or syntax used in this benchmark. The code uses standard ES5 features and syntax.
Other Alternatives
If you're looking for alternatives to forEach
, some options include:
map()
: Can be used to transform the array while iterating, but may not be as suitable for simple iteration use cases.reduce()
: Can be used to accumulate values from an array, but may not be as efficient as forEach
for pure iteration use cases.Benchmark Preparation Code
The benchmark preparation code is empty, which means that the script will start execution from scratch with each test case.
Individual Test Cases
There are two test cases:
**: This test case measures the performance of a traditional
for` loop approach.**: This test case measures the performance of the
forEach` method approach.The benchmark results show that the Chromium 52 browser performs better on the "for loop" test case, with an average execution rate of approximately 11,066.45 executions per second. The same browser performs worse on the "for each" test case, with an average execution rate of approximately 4,391.07 executions per second.
Keep in mind that these results may vary depending on the specific use case and environment in which the benchmark is run.