var idToGet = ''
function uuidv4() {
return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
var r = Math.random() * 16 | 0, v = c == 'x' ? r : (r & 0x3 | 0x8);
return v.toString(16);
});
}
var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = {id: uuidv4(), idx: i};
}
var item = arr[Math.floor(Math.random() * arr.length)];
idToGet = item.id
function someFn(i) {
return i.id === idToGet
}
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 | 11844.7 Ops/sec |
for | 7690.5 Ops/sec |
map | 11458.4 Ops/sec |
Let's dive into explaining the provided benchmark.
Benchmark Definition
The test compares three approaches to iterate through an array of objects in JavaScript: forEach
, for
loops, and map
with a callback function.
Options Compared
forEach
: This method iterates through an array using a closure (a self-executing anonymous function) that is called for each element in the array.for
Loops: This traditional approach uses a manual loop counter to iterate through the array, where each iteration checks if the current index is within the bounds of the array.map
with callback function: The map
method creates a new array by applying a provided callback function (in this case, someFn
) to each element in the original array.Pros and Cons
forEach
:for
Loops:forEach
.map
with callback function:Library and Special JS Features
In this benchmark, the following library is used:
uuidv4()
function generates a random UUID string, which is assigned as the unique identifier (idToGet
) in each array element. This suggests that the benchmark is testing the performance of different iteration methods with distinct data structures.Other Considerations
id
property and an idx
property.someFn
function is used as the callback function for both forEach
and map
, which means that it's being executed in parallel for each element. This could impact performance due to function call overhead.Alternatives
If you're interested in exploring alternative iteration methods or optimizing your code, consider the following options:
for...of
loops: Introduced in ECMAScript 2017, this syntax provides a more modern and concise way of iterating through arrays.while
loops: A traditional approach for manual loop iterations, which can be useful when dealing with complex logic or edge cases.reduce()
method: Instead of using map
to create a new array, consider using the reduce()
method to accumulate results in a single array.Please note that these alternatives might not be directly comparable to the original forEach
, for
, and map
approaches, as they have different use cases and performance characteristics.