var arr = [];
for (var i = 0; i < 10000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(function (item){
someFn(item);
})
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 1695.5 Ops/sec |
for | 1032.5 Ops/sec |
map | 1700.3 Ops/sec |
Let's break down the provided JSON and explain what is being tested.
Benchmark Definition
The benchmark defines three test cases:
foreach
: Uses the forEach
method to iterate over an array, calling the someFn
function on each element.for
: Uses a traditional for
loop to iterate over an array, calling the someFn
function on each element.map
: Uses the map
method to create a new array with transformed elements, calling the someFn
function on each element.Script Preparation Code
The script preparation code creates an array of 10,000 elements and defines a simple function someFn
that takes an integer i
as input and returns i * 3 * 8
.
Html Preparation Code
There is no HTML preparation code provided.
Options Compared
The benchmark compares the performance of three different approaches:
forEach
: Uses the forEach
method to iterate over an array.for
loop: Uses a traditional for
loop to iterate over an array.map
: Uses the map
method to create a new array with transformed elements.Pros and Cons
Here are some pros and cons of each approach:
forEach
:forEach
method.for
loop:map
:Library and Purpose
The forEach
, for
, and map
methods are built-in JavaScript methods. They provide an alternative way to iterate over arrays or create new arrays with transformed elements, respectively.
Special JS Feature or Syntax
There is no special JS feature or syntax used in this benchmark.
Other Alternatives
Some other alternatives for iterating over arrays include:
Array.prototype.forEach.call()
: This method calls the forEach
method on an array-like object.Array.prototype.reduce()
: This method reduces an array to a single value by applying a callback function to each element.Array.prototype.filter()
: This method creates a new array with filtered elements.Keep in mind that these alternatives may have different performance characteristics and use cases compared to the forEach
, for
, and map
methods.