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]);
}
for (const a of arr) {
someFn(a);
}
arr.forEach(function (item){
someFn(item);
})
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
For/of | |
Foreach | |
Map |
Test name | Executions per second |
---|---|
For | 3992.3 Ops/sec |
For/of | 7872.6 Ops/sec |
Foreach | 6762.1 Ops/sec |
Map | 8447.9 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark that compares the performance of four different approaches: for
loop, for/of
loop, forEach
loop, and map
method.
Options Compared
The options compared in this benchmark are:
for
loop with an index variable (i
) to iterate over the array elements.for/of
loop that uses a for-of statement to iterate over the array elements, which is more concise and expressive than traditional for
loops.forEach
method that iterates over an array of values using a callback function.map()
method creates a new array with the results of applying a provided function to every element in this array.Pros and Cons of Each Approach
for
loops, easier to read and maintain.map()
method, which might not be available in older browsers.Library Used (if applicable)
In this benchmark, none of the options use an external library. However, if we consider the forEach
loop and map
method as part of the ECMAScript standard, they are built-in functions provided by JavaScript.
Special JS Features or Syntax
map()
method was introduced in ECMAScript 2009 (ES5) as part of the standard library.Other Alternatives
If you need to iterate over an array or create a new array with transformed values, other alternatives might be:
reduce()
: A function that applies a reduction function to each element in an array and returns a single value.arr.forEach(function(item) { /* do something */ });
)Keep in mind that these alternatives might have different performance characteristics and use cases compared to the options tested in this benchmark.
Tips for Software Engineers
When working with JavaScript, it's essential to consider the trade-offs between conciseness, readability, performance, and compatibility when choosing an iteration approach. In general:
for/of
loops when you need concise and expressive code, and your target browser supports ES7+ syntax.for
loops or forEach
loops when you need more control over the iteration process or when supporting older browsers is necessary.map()
method when creating a new array with transformed values, but be aware of performance implications if dealing with large datasets.