var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
for(let item of arr){
someFn(item);
}
arr.forEach(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
map | |
for of | |
forEach |
Test name | Executions per second |
---|---|
for | 2857.6 Ops/sec |
map | 3750.7 Ops/sec |
for of | 3915.7 Ops/sec |
forEach | 3862.7 Ops/sec |
Let's break down the provided benchmark and its individual test cases.
Benchmark Definition
The benchmark is designed to compare four different approaches for iterating over an array: for
, foreach
, map
, and another for
loop. The script preparation code creates an empty array arr
with 1000 elements, each initialized with a value from 0 to 999. A function someFn
is also defined, which takes an integer as input and returns the result of multiplying it by 3 and 8.
Individual Test Cases
Each test case represents one of the four iteration approaches:
**: This test case uses a traditional
for` loop to iterate over the array elements.**: This test case utilizes the
Array.prototype.map()` method, which applies a given function to each element in the array and returns a new array with the results.**: This test case employs the
for...of` loop, which is a modern iteration syntax introduced in ECMAScript 2015 (ES6).**: This test case uses the
Array.prototype.forEach()` method, which executes a provided function once for each array element.Options Comparison
Here's an overview of the pros and cons for each approach:
try-catch
.map
, but without the need to create a new array, suitable for simple iteration tasks.undefined
.Library and Special JS Features
In this benchmark, there is no explicit mention of any libraries being used. However, it's worth noting that some modern browsers may optimize certain functions using WebAssembly (WASM) or other low-level features.
No special JavaScript features are explicitly mentioned in the benchmark definition or test cases.
Alternatives and Considerations
If you're considering alternatives to these approaches:
while
loops or indexing-based approaches.reduce()
, every()
, or other higher-order functions.In conclusion, this benchmark provides a useful comparison of four common array iteration approaches in JavaScript. By understanding the strengths and weaknesses of each approach, developers can choose the most suitable method for their specific use cases.