var arr = [];
for (var i = 0; i < 10000; i++) {
arr[i] = Math.round(Math.random(0,9999));
}
var copy1 = [], copy2 =[], copy3 = [];
arr.forEach((el,i) => {
copy1[i] = el * 3
});
for (var i = 0, l = arr.length; i < l; i++) {
copy2[i] = arr[i] * 3;
};
copy3 = arr.map(el => el * 3)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
map |
Test name | Executions per second |
---|---|
foreach | 1350.3 Ops/sec |
for | 803.4 Ops/sec |
map | 16534.4 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of three different approaches for iterating over an array and performing calculations on its elements: forEach
, for
loop, and map
. The test case generates a large array of random numbers, creates copies of it using each approach, and then calculates the product of each element by multiplying it with 3.
Comparison of Approaches
forEach
method, which calls a provided callback function once for each element in the array. In this test case, the callback function multiplies each element by 3 and assigns the result to the corresponding index in the copy array.forEach
method.for
loop with an iterator variable i
, which iterates over the array elements and assigns them to the corresponding index in the copy array.forEach
as it avoids the overhead of callback function calls, but may require more code to set up.forEach
, making it less readable.map
method, which creates a new array with the results of applying a provided transformation function to each element in the original array. In this test case, the transformation function multiplies each element by 3 and returns the result.forEach
as it leverages the built-in map
method and avoids explicit loops, making it more concise.Library and Special Features
The test case uses two built-in JavaScript features:
Other Alternatives
While not explicitly tested, other alternatives could be:
loop (using
for...of)**: Instead of using the
forEachmethod, you can use a traditional
for...of` loop to iterate over the array elements.forEach
: Lodash is a popular utility library that provides a more extensive set of functions for iterating over arrays, including a forEach
function.filter
, reduce
, every
): Depending on the specific use case, other iteration methods might be more suitable than forEach
.Benchmarking Considerations
When benchmarking these approaches, it's essential to consider factors such as:
By understanding the pros and cons of each approach, developers can choose the most suitable method for their specific use case.