var arr = [];
for(let i = 0; i < 10000; i++) {
arr.push(Math.random());
}
var arrLength = arr.length;
let sum = 0;
for(const num of arr) {
sum += num;
}
let sum = 0;
for(let i = 0; i < arrLength; i++) {
sum += arr[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Iterator for loop | |
Index for loop |
Test name | Executions per second |
---|---|
Iterator for loop | 19373.6 Ops/sec |
Index for loop | 22203.7 Ops/sec |
Let's dive into the provided benchmark and explain what is being tested.
The test compares two approaches to iterate over an array: using an iterator (forEach) versus using index-based indexing ( traditional for loops). The array length is fixed at 10,000 elements, which is already cached before running the benchmarks.
Pros and Cons of each approach:
const
and avoiding unnecessary variable assignments)Library:
There is no explicitly mentioned library in this benchmark, but forEach
(also known as "for...of" loop) is a built-in JavaScript feature that leverages the V8 engine's iterator implementation. The test is comparing the performance of using the built-in forEach
method versus traditional for loops.
Special JS Features:
This benchmark does not use any special JavaScript features or syntax beyond the standard language and the provided libraries (V8 engine).
Alternative Benchmarks:
Other alternatives to compare in this type of benchmark could include:
map()
or reduce()
Keep in mind that the choice of alternatives depends on the specific use case and requirements of the benchmark.