let array = new Array(100);
for (let i = 0; i < array.length; i++) {
array[i];
}
array.forEach((i) => {
array[i];
});
array.some((i) => {
array[i];
});
for (let i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 4121621.5 Ops/sec |
foreach | 4283674.0 Ops/sec |
some | 4199692.5 Ops/sec |
for..of | 935826.7 Ops/sec |
The benchmark defined in the provided JSON is focused on comparing the performance of various looping constructs in JavaScript. This benchmark specifically evaluates four different looping methods:
Traditional for loop:
for (let i = 0; i < array.length; i++) {
array[i];
}
Pros:
Cons:
Array.prototype.forEach:
array.forEach((i) => {
array[i];
});
Pros:
Cons:
Array.prototype.some:
array.some((i) => {
array[i];
});
Pros:
Cons:
for..of loop:
for (let i of array) {
array[i];
}
Pros:
Cons:
According to the benchmark results gathered from testing on Chrome 131 running on macOS, the performance outcomes in terms of executions per second are as follows:
Aside from the four methods evaluated in the benchmark, other alternatives for iteration in JavaScript include:
While Loop: This is a traditional looping construct that provides extensive control over iteration but can be less readable and prone to errors if the termination condition is not handled correctly.
Do-While Loop: Similar to the while loop but guarantees that the loop body will execute at least once. This can be beneficial in some cases but introduces complexity in managing the loop conditions.
Array.prototype.map: Although primarily used for transforming arrays rather than iteration, it could also be used to iterate through an array with cleaner syntax. However, like forEach and some, it incurs a similar performance penalty due to the function call overhead.
The benchmark presents a useful comparison of various looping techniques in JavaScript. While the traditional for loop often exhibits the best performance, newer methods like forEach and for..of improve code readability and maintainability. Developers should choose the method that balances performance needs with code clarity based on the specific context in which it is used.