var arr1 = [];
for(i=0; i<10000; i++){arr1.push(i);}
for (const i of arr1) { i + 1; }
for (const i of arr1.slice(1)) { i + 1; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-of normal loop | |
for-of slice |
Test name | Executions per second |
---|---|
for-of normal loop | 74841.5 Ops/sec |
for-of slice | 46015.7 Ops/sec |
I'd be happy to help explain the provided benchmark.
Benchmark Overview
The benchmark tests two approaches for iterating over arrays using for...of
loops:
for...of
loop with no slicing of the array (arr1
).for...of
loop with slicing of the first element of the array (arr1.slice(1)
).Script Preparation Code
The script preparation code generates a large array arr1
with 10,000 elements, and then initializes it by pushing numbers from 0 to 9,999 onto the array using a traditional for
loop.
Options Compared
The benchmark compares two options:
for...of
loop: This approach iterates over the entire array in one pass.for...of
loop with slicing of the first element of the array (arr1.slice(1)
): This approach creates a new, smaller array by slicing off the first element from the original array.Pros and Cons
Normal for...of
Loop:
Pros:
Cons:
For-of loop with Slicing:
Pros:
Cons:
Library:
None
Special JS Feature/Syntax:
This benchmark does not use any special JavaScript features or syntax beyond the for...of
loop.
Other Considerations
The benchmark assumes that the browser is running on a desktop platform with Safari 17. Other browsers and platforms may have different performance characteristics.
Alternatives
Other alternatives for iterating over arrays using for...of
loops include:
Array.prototype.forEach()
or other array methods, which can provide similar performance benefits to slicing.for
loops, which can offer better control over the iteration process but may not take advantage of browser optimizations.It's worth noting that the choice of iteration approach ultimately depends on the specific use case and requirements of the application.