var array = new Array(100);
array.forEach(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for..of |
Test name | Executions per second |
---|---|
foreach | 14662969.0 Ops/sec |
for..of | 2138129.2 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The "foreach vs for...of" benchmark compares the performance of two loop constructs in JavaScript: forEach
and for...of
. The test case uses an array with 100 elements to compare the execution times of both loops.
Loop Constructs Compared
Two loop constructs are compared:
forEach
: This is a built-in method on arrays that iterates over each element, calling the provided callback function for each iteration.for...of
: This is a new loop construct introduced in ECMAScript 2015 (ES6) that allows iterating over iterable objects, such as arrays.Options Compared
The benchmark compares two options:
forEach
: The first option uses the forEach
method to iterate over the array.for...of
: The second option uses the for...of
loop construct to iterate over the array.Pros and Cons of Each Approach
Here are some pros and cons of each approach:
forEach
:for...of
:i
) and incrementing its value manually.Library Used
There is no explicit library used in the benchmark. However, it's worth noting that some browsers may use internal libraries or optimizations to execute JavaScript loops, which can affect the results of the benchmark.
Special JS Features/Syntax
The test case uses ES6 features:
for...of
loop construct\r\n
) in the script preparation codeOther Considerations
When comparing loop performance, it's essential to consider other factors that might impact execution time, such as:
Alternative Benchmarks
Some alternative benchmarks that compare loop constructs include:
These alternatives can provide more comprehensive insights into the performance characteristics of various loop constructs, as well as other aspects of JavaScript execution.