var array = Array.from({length: 100}, (_, index) => index);
var sum = 0
for (var i = 0; i < array.length; i++) {
sum += array[i];
}
var sum = 0
array.forEach(function(item) {
sum += item;
});
var sum = 0
for (var item of array) {
sum += item;
}
var sum = 0
for (var i = array.length; i--;) {
sum += array[i];
}
var sum = array.reduce((sum, item) => sum + item, 0)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
forEach | |
for-of | |
for-reverse | |
reduce |
Test name | Executions per second |
---|---|
for | 78948.9 Ops/sec |
forEach | 3955648.0 Ops/sec |
for-of | 5644931.5 Ops/sec |
for-reverse | 154496.1 Ops/sec |
reduce | 6602774.0 Ops/sec |
The provided JSON represents a benchmark test case created on MeasureThat.net, which compares the performance of different JavaScript loop constructs: for, forEach, for-of, and for-reverse. The test case also includes a reduce method for comparison.
Here's an explanation of each option:
array[i]
) or with traditional for loops (e.g., for (var i = 0; i < array.length; i++)
).--
operator to decrement a counter variable, making it more concise and easier to read than traditional for loops with manual indexing.The test case measures the performance of these different loop constructs and methods on various devices and browsers. The results show that:
Other alternatives that could be used instead of these loop constructs include:
However, since the test case is specifically designed to compare the performance of loop constructs and methods in array iteration, these alternatives are not considered part of the primary comparison.