var arr =new Array(10000);
let i=0;
while(i < arr.length) {
const exp = arr[i] ** 2;
i++;
}
for(let i=0; i<arr.length; i++) {
const exp = arr[i] ** 2;
}
arr.forEach((element) => {
const exp = element ** 2;
});
for(const element of arr) {
const exp = element ** 2;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
while | |
for | |
forEach | |
for of |
Test name | Executions per second |
---|---|
while | 969.7 Ops/sec |
for | 892.2 Ops/sec |
forEach | 84817.3 Ops/sec |
for of | 338432.1 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
The benchmark compares four different approaches to iterate over an array of length 10,000:
while
loop with a conditional statement to check if the index is within the bounds of the array.for
loop with an initialization, condition, and increment clause to iterate over the array.forEach
method provided by modern JavaScript arrays, which allows iterating over an array without explicit indexing or looping logic.for...of
loop.Options being compared:
The benchmark compares the performance of each approach on a specific test case, which calculates the square of each element in the array using exponentiation (arr[i] ** 2
). The goal is to measure the execution time (in executions per second) for each approach.
Pros and cons of each approach:
The for...of
loop is the clear winner in this benchmark, with an execution time significantly lower than the other approaches. This is likely due to its optimized nature and the fact that it's specifically designed for array iteration.
Library usage:
There is no explicit library used in these test cases. However, modern JavaScript engines like Chrome provide optimizations for the forEach
method, which contributes to its improved performance in this benchmark.
Special JS features or syntax:
The for-of loop introduced in ES6 is a special feature that allows iterating over arrays and other iterable objects using a concise syntax. It's not a library per se, but rather a new syntax added to the language.
Overall, this benchmark provides valuable insights into the performance characteristics of different iteration approaches in JavaScript. The results can help developers choose the most suitable approach for their specific use cases and optimize their code accordingly.