const data = Array.from({length: 10000}, () => Math.floor(Math.random() * 1000));
let sum = 0;
for (let i=0; i < data.length; i++){
sum += data[i];
}
const data = Array.from({length: 10000}, () => Math.floor(Math.random() * 1000));
let sum = 0;
for (const n of data){
sum += n;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For loop | |
For of loop |
Test name | Executions per second |
---|---|
For loop | 3931.0 Ops/sec |
For of loop | 2929.5 Ops/sec |
Let's break down the benchmark and explain what is being tested, compared, and their pros and cons.
Benchmark Overview
The benchmark compares two approaches to iterate over an array: traditional for
loop and for...of
loop. The test case uses JavaScript arrays with random integer values and calculates the sum of all elements in each iteration.
Options Compared
for
Loop: This approach uses a manual index variable (i
) to keep track of the current element being processed.For...of
Loop: This approach uses the iterator protocol to iterate over the array, which eliminates the need for an explicit index variable.Pros and Cons
for
Loop:For...of
Loop:Library Used
None explicitly mentioned in the benchmark definition. However, JavaScript's built-in Array.prototype.forEach()
method is implicitly used for the For...of
loop implementation.
Special JS Feature/Syntax
None explicitly mentioned in the benchmark definition.
Other Alternatives
For other iteration methods, consider:
for...in
Loop: Iterates over an object's enumerable properties, not suitable for arrays.In conclusion, this benchmark tests the performance difference between traditional for
loop and For...of
loop in JavaScript. The results suggest that For...of
loop is generally faster due to reduced overhead and fewer indexing errors. However, this may depend on specific use cases and optimizations.
Keep in mind that JavaScript engines might optimize these loops differently, so the performance differences might vary across different browsers and environments.