var arr = [];
for (var i = 0; i < 20; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 + 8;
}
arr.forEach(someFn)
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
arr.map(someFn)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 852296.1 Ops/sec |
for | 116139.0 Ops/sec |
map | 662727.3 Ops/sec |
Benchmark Overview
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark definition json represents a test case that compares the performance of three different approaches: foreach
, for
loop, and map()
function.
What's being tested?
The benchmark tests the execution time of each approach on small arrays with 20 elements. The array is initialized with values from 0 to 19 using a for
loop. A simple function someFn(i)
is defined to take an integer value i
and return its triple plus 8.
Options compared
Three options are compared:
foreach
: Uses the forEach()
method to iterate over the array.for
: Uses a traditional for
loop to iterate over the array.map()
: Uses the map()
function to create a new array with transformed values.Pros and Cons of each approach:
foreach
:for
loop:map()
function:Library and its purpose
The forEach
method is a built-in JavaScript method that iterates over an array and executes a callback function for each element. The map()
function also iterates over an array and creates a new array with transformed values.
In the benchmark, both foreach
and map()
use these libraries to perform their respective operations on the input array.
Special JS feature or syntax
There is no special JS feature or syntax used in this benchmark. The code only uses standard JavaScript syntax and built-in functions.
Other alternatives
Alternative approaches could include:
reduce()
function instead of forEach
or map
.However, these alternatives would likely change the focus of the benchmark and may not provide a fair comparison with the original three approaches.