let items = [];
for (let i = 0; i < 100; i++) {
items.push({
something: i
});
}
window.items = items;
let items = window.items;
let theThing;
items.forEach(i => {
let item = i.something;
if (theThing || i === 3) {
theThing = i + 3;
}
});
return theThing;
let items = window.items;
let theThing;
let len = items.length;
for (let i = 0; i < len; i++) {
let item = items[i].something;
if (theThing || item === 3) {
theThing = item + 3;
}
}
return theThing;
let items = window.items;
let theThing;
for (let i = 0; i < items.length; i++) {
let item = items[i];
if (theThing || item === 3) {
theThing = item + 3;
}
}
return theThing;
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
Cache len | |
No cache len |
Test name | Executions per second |
---|---|
forEach | 3080609.0 Ops/sec |
Cache len | 5069695.0 Ops/sec |
No cache len | 3258731.5 Ops/sec |
Benchmark Explanation
The provided benchmark measures the performance of three different approaches for a specific task: iterating over an array to find and update a value.
Task Description
The task is to iterate over an array of objects, where each object has a "something" property. The goal is to find the first occurrence of a certain condition (in this case, item === 3
) and update a variable (theThing
) with the result of adding 3 to the matched value.
Approach Comparison
There are three approaches compared in this benchmark:
forEach
: Uses the forEach
method to iterate over the array. This approach is often preferred for its concise syntax and ease of use.len
: Caches the length of the array before the loop, reducing the number of iterations required to access the array's length property.len
: Does not cache the array length, requiring repeated lookups during iteration.Pros and Cons
forEach
:len
:len
:Library Usage
The benchmark uses the window.items
property as an example array, suggesting that it is a global variable or a DOM element containing the data. The forEach
method is also used, which implies that the browser supports ECMAScript 5 (ES5) or later versions of JavaScript.
Special JS Features/Syntax
There are no special JavaScript features or syntax used in this benchmark, such as async/await, Promises, or other advanced constructs.
Other Alternatives
Other approaches to iterating over an array and updating a value might include:
for
loops with explicit indexing (i = 0; i < arr.length; i++
)map()
, filter()
, and reduce()
for more functional programming-inspired solutions