function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
r: 0,
});
}
return result;
}
const array = generateTestArray();
array.forEach((x) => {
x.r = x.a + x.b;
});
const array = generateTestArray();
for(const x of array) {
x.r = x.a + x.b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.forEach | |
for..of |
Test name | Executions per second |
---|---|
.forEach | 15.5 Ops/sec |
for..of | 22.1 Ops/sec |
Benchmark Overview
The provided benchmark measures the performance of two different approaches for iterating over an array: the traditional .forEach
method and the newer for...of
loop.
Options Compared
Two options are compared:
.forEach
: A traditional method for iterating over an array, where each element is passed to a callback function.for...of
: A new syntax introduced in ECMAScript 2015 (ES6) for iterating over arrays and other iterable objects.Pros and Cons
.forEach
:for...of
:.forEach
.Library Usage
None of the benchmark tests use a specific library. The test cases only involve built-in JavaScript features.
Special JS Features/Syntax
The for...of
loop is a special feature introduced in ES6 (ECMAScript 2015) for iterating over arrays and other iterable objects. It provides a more concise way to iterate over collections of values without the need for explicit indexing or callbacks.
Other Alternatives
If you're interested in exploring other alternatives, here are a few:
.map()
: While not designed specifically for iteration, .map()
can be used to transform arrays by applying a callback function to each element.reduce()
: Another built-in JavaScript method that can be used for iterating over arrays, but it's primarily used for reducing the array to a single value.Benchmark Considerations
When creating benchmarks like this one, consider the following:
By considering these factors, you can create a robust and informative benchmark that helps identify performance differences between different JavaScript iteration methods.