const items = Array.from({length: 1000000}, () => Math.floor(Math.random() * 40));
let index = 0;
items.forEach(i => index++);
const items = Array.from({length: 1000000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i in items) {
index++;
}
const items = Array.from({length: 1000000}, () => Math.floor(Math.random() * 40));
let index = 0;
for (let i of items) {
index++;
}
const items = Array.from({length: 1000000}, () => Math.floor(Math.random() * 40));
let index = 0;
for(let i = 0; i < items.length; ++i) {
index++;
}
const items = Array.from({length: 1000000}, () => Math.floor(Math.random() * 40));
let index = 0;
for(let i = items.length; i > 0; --i) {
index++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for-in | |
for-of | |
for | |
optimized-for |
Test name | Executions per second |
---|---|
foreach | 68.6 Ops/sec |
for-in | 27.8 Ops/sec |
for-of | 77.6 Ops/sec |
for | 93.9 Ops/sec |
optimized-for | 94.4 Ops/sec |
The benchmark defined in the JSON provided evaluates the performance of different looping constructs in JavaScript when iterating through a large array of one million elements. The main options compared are:
forEach
method to iterate over items.for...in
loop, which iterates over the enumerable properties of an object.for...of
loop, designed to iterate over iterable objects (like arrays).forEach:
break
or return
statements to stop iteration early).for-in:
for-of:
for:
forEach
or for-of
.optimized-for:
for
, especially for those unfamiliar with array operations.Frameworks and Libraries: No external libraries are used in these tests, as the benchmark relies solely on native JavaScript features.
Performance: The results show that both the traditional for
and the optimized-for
approaches yield the highest executions per second around 5.76, suggesting that these raw loops perform best for large datasets. This is followed by for-of
, forEach
, and the for-in
structure, which performed the slowest.
Apart from the constructs tested in the benchmarks, there are other constructs worth mentioning for array iteration:
Array.prototype.map(): Similar to forEach
, it executes a provided function once for each array element, but it also creates a new array with the results.
Array.prototype.filter(): Allows you to iterate over the elements while filtering them based on a condition and creating a new array with only the elements that meet the criteria.
Array.prototype.reduce(): Not only iterates but can also be used to accumulate results, creating a single output value from an array.
Each of these has its use cases, and the choice often depends on the specific requirements for readability, maintainability, and performance. Understanding the trade-offs helps engineers make informed choices when writing JavaScript code, especially in performance-sensitive applications.