function generateTestArray() {
const result = [];
for (let i = 0; i < 1000000; ++i) {
result.push({
a: i,
b: i / 2,
r: 0,
});
}
return result;
}
var array = generateTestArray();
array.forEach((x) => {
x.r = x.a + x.b;
});
for (const obj of array) {
obj.r = obj.a + obj.b;
}
for (let i = 0; i < array.length; ++i) {
array[i].r = array[i].a + array[i].b;
}
const len = array.length;
for (let i = 0; i < len; ++i) {
array[i].r = array[i].a + array[i].b;
}
for (let i = 0; i < array.length; ++i) {
const x = array[i];
x.r = x.a + x.b;
}
const len = array.length;
for (let i = 0; i < len; ++i) {
const x = array[i];
x.r = x.a + x.b;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Array.forEach | |
for of | |
for <array.length, indexing | |
for <len, indexing | |
for <array.length, tmp element | |
for <len, tmp element |
Test name | Executions per second |
---|---|
Array.forEach | 120.6 Ops/sec |
for of | 515.4 Ops/sec |
for <array.length, indexing | 6.7 Ops/sec |
for <len, indexing | 8.8 Ops/sec |
for <array.length, tmp element | 13.0 Ops/sec |
for <len, tmp element | 24.2 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Description
The benchmark measures the performance of different ways to iterate over an array in JavaScript. The test case creates a large array with 1 million elements, each containing three properties: a
, b
, and r
. The script then performs an operation on each element in the array, either by updating the value of r
based on the values of a
and b
.
Benchmark Options
The benchmark compares four different ways to iterate over the array:
array[i]
) to access each element in the array.x
to hold each element of the array.Pros and Cons of Each Approach
array[i]
).Library and Special JS Features
The benchmark does not use any external libraries. However, it assumes that the Array
object is available, which is a built-in JavaScript object. There are no special JavaScript features used in this benchmark.
Other Considerations
generateTestArray()
function creates an array with 1 million elements, which may not be representative of real-world scenarios. In practice, arrays are often smaller and more manageable.array
variable is accessible within each iteration.Alternatives
If you want to explore alternative approaches or modifications to this benchmark, consider: