var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = {
name: `${i}`,
value: i
};
}
function someFn(i) {
const x24 = i.value * 3 * 8;
i.value = x24;
i.name = `${x24}`;
return i;
}
const x = []
for (var y of arr) {
x.push(someFn(y));
}
arr.map(item => someFn(item))
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for of | |
map |
Test name | Executions per second |
---|---|
for of | 31138.2 Ops/sec |
map | 33171.8 Ops/sec |
Let's break down the provided JSON and benchmark.
Benchmark Definition
The benchmark is designed to compare two approaches for iterating over an array in JavaScript:
for...of
loop, which is a more modern way of iterating over arrays and other iterable objects.map()
method, which applies a function to each element of an array and returns a new array with the results.Options Compared
The two options being compared are:
for (const y of arr) { ... }
arr.map(item => someFn(item))
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
For-of Loop
Pros:
for...of
with Array.from()
or Promise.all()
)Cons:
Array.prototype.map()
Pros:
forEach()
, filter()
, and reduce()
.Cons:
Other Considerations
In this benchmark, we're also interested in the JavaScript runtime (V8) used by each browser. The provided raw UA string indicates that both browsers use Firefox 114 on a Linux desktop.
Now, let's look at the individual test cases:
Test Case 1: For-of Loop
The test case uses the for...of
loop to iterate over the array and call the someFn()
function for each element. The const x = []
initialization creates an empty array that will be populated with results from the someFn()
calls.
Library/Function: None
This is a built-in JavaScript feature, and no external library or module is required.
Special JS Feature/Syntax: For-of loop (not exactly a "feature" but rather a new syntax introduced in ECMAScript 2015)
Test Case 2: Array.prototype.map()
The test case uses the map()
method to apply the someFn()
function to each element of the array. The resulting array is not used, and the focus is on measuring the execution time of this approach.
Library/Function: Array.prototype.map()
This method is a built-in part of the JavaScript standard library (ECMAScript 262).
Overall, the benchmark provides a simple yet informative way to compare two common approaches for iterating over arrays in JavaScript. The results can help developers choose the most suitable approach depending on their specific use case and performance requirements.