var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(ix) {
return ix * 5 + 1 / 3 * 8;
}
for (var i = 0; i < arr.length; i++) {
someFn(arr[i]);
}
var i = 0;
while (i < arr.length) {
someFn(arr[i]);
i++;
}
for (var i = 0, len = arr.length; i < len; i++) {
someFn(arr[i]);
}
var len = arr.length;
for (var i = 0; i < len; i++) {
someFn(arr[i]);
}
for (var i = arr.length; i > 0; i--) {
someFn(arr[i]);
}
var i = arr.length;
for (; i--;) {
someFn(arr[i]);
}
var len = arr.length;
var i = 0;
while(i < len){
someFn(arr[i]);
i++;
}
var i = arr.length;
while(i--){
someFn(arr[i]);
}
arr.forEach(function(arrI){
someFn(arrI);
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For loop, basic | |
While loop, basic | |
For loop, cached (inside for statement) | |
For loop, cached (outside for statement) | |
For loop, i-- (caching inside for loop) | |
For loop, i-- (caching outside for loop) | |
While loop, cached | |
While loop, i-- | |
forEach |
Test name | Executions per second |
---|---|
For loop, basic | 4090.4 Ops/sec |
While loop, basic | 4199.2 Ops/sec |
For loop, cached (inside for statement) | 6324.0 Ops/sec |
For loop, cached (outside for statement) | 6270.9 Ops/sec |
For loop, i-- (caching inside for loop) | 6440.5 Ops/sec |
For loop, i-- (caching outside for loop) | 6575.9 Ops/sec |
While loop, cached | 6004.6 Ops/sec |
While loop, i-- | 6242.0 Ops/sec |
forEach | 12254.4 Ops/sec |
Measuring the performance of different programming constructs is essential to understand how various approaches can impact an application's efficiency.
Benchmark Overview
The provided benchmark measures the execution time of different for/while loops in JavaScript, specifically with regards to caching (i.e., reusing the loop variable or its length). The test cases cover various scenarios:
Options Compared
The benchmark compares the performance of four options:
A) Basic for loop: A standard for loop that doesn't cache the index or its length. B) Basic while loop: A traditional while loop without caching any variables. C) For loop with cached index (inside): A for loop where the index is declared inside the loop and reused on each iteration. D) For loop with cached index (outside): A for loop where the index is declared outside the loop and reused on each iteration.
Pros and Cons of Each Approach
Benchmark Results
The provided benchmark results show that:
Conclusion
The benchmark highlights the importance of optimizing loops in JavaScript applications. By using techniques like caching the index, developers can significantly reduce execution times, especially when dealing with large datasets or computationally expensive loop bodies. The results demonstrate that both for loop approaches (C and D) outperform traditional while loops (B), reinforcing the benefits of caching the index.