<script>
Benchmark.prototype.setup = function() {
var testData = [];
for (var i = 0; i < 100; i++) {
testData.push(i);
}
};
</script>
let res = 0;
testData.forEach(function(x) {
res += x;
});
let res = 0;
for (let i = 0; i < testData.length; i++) {
res += testData[i];
}
let res = 0;
for (let i = 0, len = testData.length; i < len; i++) {
res += testData[i];
}
var res = testData.reduce(function(sum, x) {
return sum + x;
}, 0);
var res = 0;
var i = testData.length;
while (i--) {
res += testData[i];
}
var res = 0;
for (let data in testData) {
res += testData[data];
}
var res = 0;
for (var data of testData) {
res += data;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
for | |
for optimized | |
reduce | |
while | |
for in | |
for of |
Test name | Executions per second |
---|---|
forEach | 2856881.0 Ops/sec |
for | 5963750.0 Ops/sec |
for optimized | 5198497.5 Ops/sec |
reduce | 931247.1 Ops/sec |
while | 4406619.5 Ops/sec |
for in | 325876.5 Ops/sec |
for of | 1272847.4 Ops/sec |
The benchmark conducted at MeasureThat.net evaluates the performance of various JavaScript iteration methods. Specifically, it compares the following constructs:
forEach: This method iterates over each element in the array and executes a provided function on each element.
for: The classic for loop that allows iteration through an array using an index.
for optimized: This variation of the for loop precomputes the length of the array outside the loop to reduce computation time within the loop.
reduce: This method reduces the array to a single value by executing a reducer function on each element.
while: Utilizes a while-loop to iterate until a specified condition is met.
for in: This loop iterates over the enumerable properties of an object.
for of: This ES6 syntax allows iteration over iterable objects such as arrays directly returning their values.
From the benchmark results executed on the Chrome 131 browser, the "for optimized" loop exhibited the highest performance with approximately 8.3 million executions per second, closely followed by the traditional "for" loop. The "while" and "reduce" followed, showing moderate performance, while "for of" and "forEach" showed slower performance comparatively. The "for in" iteration was the slowest, emphasizing its unsuitability for array traversal.
reduce
may be more appropriate despite potentially lower performance. By evaluating these iteration methods, developers can make informed choices that balance performance, readability, and maintainability tailored to their application’s needs.