var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i] = i * 10000
}
for (let i = 0; i < array.length; i++) {
array[i] + 1
}
array.forEach((i) => {
array[i] + 1
});
for (let i = 0, length = array.length; i < length; i++) {
array[i] + 1
}
for (var i of array) {
array[i] + 1
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for (cached length) | |
for..of |
Test name | Executions per second |
---|---|
for | 43037.9 Ops/sec |
foreach | 84180.4 Ops/sec |
for (cached length) | 84712.8 Ops/sec |
for..of | 82988.3 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript microbenchmark test case on the MeasureThat.net website. The benchmark compares the performance of four different loop constructs: traditional for
loops, foreach
loops, and two variations of for
loops with caching: one that uses a cached variable for the array length, and another that uses the of
syntax.
What is tested?
The test case measures the execution speed (measured in executions per second) of each loop construct as they iterate over an array of 100 elements. The array is populated with values using the initial script preparation code: array[i] = i * 10000
. In each iteration, a simple increment operation is performed on each element: array[i] + 1
.
Options compared
The four loop constructs are compared as follows:
for
loops: A classic loop construct that uses a manually incremented index variable.foreach
loops: A loop construct that iterates over an array using the forEach
method, which is equivalent to a traditional for
loop but with a more concise syntax.for (cached length)
: A variation of the traditional for
loop that uses a cached variable for the array length, reducing the overhead of recalculating the length in each iteration.for..of
loops: A modern loop construct introduced in ECMAScript 2015, which allows iterating over an array using a more concise syntax.Pros and cons
Here's a brief summary of the pros and cons of each approach:
for
loops:foreach
loops:forEach
method invocation.for (cached length)
:for..of
loops:Library usage
None of the loop constructs use any external libraries. The forEach
method is a built-in JavaScript method that iterates over an array using a callback function.
Special JS features or syntax
There are no special JavaScript features or syntax used in this benchmark. However, it's worth noting that the for..of
loop uses a new syntax introduced in ECMAScript 2015, which may not be supported by older browsers or environments.
Alternatives
If you're looking for alternatives to these loop constructs, here are a few options:
map
, filter
, and reduce
methods: These methods provide an alternative way to process arrays using functional programming principles.Keep in mind that each of these alternatives has its own trade-offs and performance characteristics, which may affect the outcome of this benchmark.