function getArr() {
return Array(1000).fill(1);
// var arr = [];
// for (var i = 0; i < 1000; i++) {
// arr[i] = i;
// }
// return arr;
}
function someFn(i) {
return i * 3 * 8;
}
var arr = getArr();
arr.forEach((item) => {
someFn(item);
})
var arr = getArr();
arr.map(item => someFn(item));
var arr = getArr();
for (var i = 0; i < arr.length; i++) {
someFn(arr[i]);
}
var arr = getArr();
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
var arr = getArr();
for (var i = arr.length - 1; i >= 0; i--) {
someFn(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
map | |
for each | |
for each cached | |
for each cached reversed |
Test name | Executions per second |
---|---|
foreach | 54208.8 Ops/sec |
map | 26685.7 Ops/sec |
for each | 79064.2 Ops/sec |
for each cached | 77794.3 Ops/sec |
for each cached reversed | 92935.9 Ops/sec |
Let's break down the provided benchmark JSON and explain what is being tested.
Benchmark Definition
The benchmark measures the performance of three different approaches to iterate over an array: foreach
, map
, and two variations of for
loops (for each cached
and for each cached reversed
). The test uses a fixed-size array of 1000 elements, filled with zeros (in reality, they're being filled with ones in the code).
Script Preparation Code
The script defines two functions: getArr()
creates an array of 1000 elements, and someFn(i)
takes an element from the array and returns its value multiplied by 3 and then by 8.
Test Cases
forEach
method, which calls someFn(item)
for each element.map
method to create a new array with transformed elements, where someFn(item)
is applied to each element.for
loop that iterates over the array length instead of the array itself.Library and Special Features
forEach
: The forEach
method is a built-in JavaScript method for iterating over arrays and other iterable objects.map
: The map
method is also a built-in JavaScript method for creating new arrays by applying a transformation function to each element of the original array.Options Compared
The options compared are:
forEach
, map
, and two variations of for
loops (for each cached
and for each cached reversed
).for
loop optimizations (i.e., whether the loop iterates over the array length or the array itself).Pros and Cons
Here are some pros and cons for each approach:
forEach
. Cons: Requires additional memory allocation and copying of elements.Other Considerations
someFn
function is inlined and optimized by the JavaScript engine. In reality, this function may be called multiple times per iteration, affecting its performance.Alternatives
If you need to compare performance of similar loops or functions, you can consider using other benchmarking frameworks, such as:
Keep in mind that each framework has its own strengths and weaknesses, so choose one that fits your specific needs.