var array = new Array(100);
var fn = function(el, idx, arr) {
el;
}
array.forEach(function(_el, idx, _arr) {
array[idx];
});
array.forEach(function(el, idx, arr) {
el;
});
array.forEach(fn);
for (const i of array) {
array[i];
}
for (var i in array) {
array[i];
}
for (var i = 0; i < array.length; i++) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array forEach, callback function provided as an argument, ignoring most callback arguments | |
Array forEach, callback function provided as an argument | |
Array forEach, callback function provided as a predefined variable | |
for..of | |
for..in | |
for loop |
Test name | Executions per second |
---|---|
Array forEach, callback function provided as an argument, ignoring most callback arguments | 5601961.0 Ops/sec |
Array forEach, callback function provided as an argument | 5600143.0 Ops/sec |
Array forEach, callback function provided as a predefined variable | 3423975.0 Ops/sec |
for..of | 733334.7 Ops/sec |
for..in | 4747800.0 Ops/sec |
for loop | 3430163.0 Ops/sec |
The benchmark defined in the provided JSON tests the performance of different iteration techniques in JavaScript, particularly for arrays. Several methods of iterating over an array are compared, including using the forEach
method with various configurations and traditional loop constructs such as for
, for...of
, and for...in
. Below is a breakdown of the approaches tested, along with their pros and cons, and other considerations.
Array forEach with Inline Callback Ignoring Arguments:
array.forEach(function(_el, idx, _arr) {
array[idx];
});
Array forEach with Full Callback:
array.forEach(function(el, idx, arr) {
el;
});
Array forEach with Predefined Function Variable:
array.forEach(fn);
fn
) can be reused, potentially improving clarity and separating logic outside of the iteration context.For...of Loop:
for (const i of array) {
array[i];
}
i
represents the actual array element, not an index.For...in Loop:
for (var i in array) {
array[i];
}
Traditional For Loop:
for (var i = 0; i < array.length; i++) {
array[i];
}
forEach
methods, especially those using inline callbacks, performed better than traditional for loops and other constructs.for...of
and for...in
loops have much lower performance and are arguably less suitable for standard array iteration tasks.In addition to the methods tested, JavaScript also supports methods like map
, filter
, and reduce
, which can be more expressive for certain use cases where transformation or filtering of arrays is required. However, these methods introduce additional complexity in their implementation, often resulting in less performance in raw iteration tasks compared to forEach
and traditional loops.
Overall, when choosing an iteration strategy, consider the specific needs of your code (readability, performance, maintainability) and the nature of the data you are working with.