function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
x: 0,
y: 0,
});
}
return result;
}
const array = generateTestArray();
for (let i = 0; i < array.length; i++) {
array[0].x = array[0].a + array[0].b;
array[0].y = array[0].a + array[0].b * 2;
}
const array = generateTestArray();
for (const a of array) {
a.x = a.a + a.b;
a.y = a.a + a.b * 2;
}
const array = generateTestArray();
array.forEach(a => {
a.x = a.a + a.b;
a.y = a.a + a.b * 2;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
For...Of | |
ForEach |
Test name | Executions per second |
---|---|
For | 38.1 Ops/sec |
For...Of | 32.8 Ops/sec |
ForEach | 31.5 Ops/sec |
Overview of the Benchmark
The provided benchmark measures the performance of different loop constructs in JavaScript: for
, for...of
, and .forEach
. The goal is to compare the execution speed of these loops on a specific test case, which creates an array of 1 million objects and updates their properties.
Loop Constructs Comparison
The traditional for
loop uses an explicit index variable (i
) to iterate over the array. It updates the index value at each iteration using ++i
.
Pros:
Cons:
The for...of
loop uses a more modern approach, iterating over arrays using a special syntax. It does not require an explicit index variable and is often considered more readable.
Pros:
Cons:
The .forEach()
method uses a callback function to process each element of an array. It provides a functional programming style for loop execution.
Pros:
Cons:
Library and Framework Considerations
In the provided benchmark, no explicit libraries or frameworks are used. However, .forEach()
is a built-in method on arrays in JavaScript. If you were to create your own loop-based implementation without this convenience, you would need to manually manage an index variable and control flow logic, which might result in less efficient code.
JavaScript Features
The benchmark does not explicitly use any special JavaScript features beyond the three loop constructs mentioned. However, it's essential to note that using for...of
or .forEach()
loops might leverage more modern language features (like support for array methods). If you're interested in exploring other advanced JavaScript features, such as async/await, Promises, or Arrow functions, feel free to consider incorporating them into your benchmark.
Alternatives and Similar Benchmarks
For those interested in exploring alternative loop constructs or performance testing tools:
.forEach()
, you could use other native array methods like map()
or reduce()
.These alternatives offer different perspectives on loop execution and performance optimization in JavaScript.