var arr = [];
for (var i = 0; i < 10000; i++) {
arr.push(i);
}
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
var i = 0;
while (i < arr.length) {
sum += arr[i];
i++;
}
for (var i = 0, len = arr.length; i < len; i++) {
sum += arr[i];
}
var len = arr.length;
for (var i = 0; i < len; i++) {
sum += arr[i];
}
for (var i = arr.length; i > 0; i--) {
sum += arr[i];
}
var i = arr.length;
for (; i--;) {
sum += arr[i];
}
var len = arr.length;
var i = 0;
while(i < len){
sum += arr[i];
i++;
}
var i = arr.length;
while(i--){
sum += arr[i];
}
arr.forEach(function(val){
sum += val;
});
--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 | 34.3 Ops/sec |
While loop, basic | 33.9 Ops/sec |
For loop, cached (inside for statement) | 45.5 Ops/sec |
For loop, cached (outside for statement) | 45.6 Ops/sec |
For loop, i-- (caching inside for loop) | 43.8 Ops/sec |
For loop, i-- (caching outside for loop) | 39.0 Ops/sec |
While loop, cached | 44.1 Ops/sec |
While loop, i-- | 46.4 Ops/sec |
forEach | 51.7 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
The provided JSON represents a benchmarking test case for comparing the performance of different JavaScript loops. The main goal is to measure which loop type and caching approach yields the best execution speed.
Here are the options being compared:
arr.length
as the condition.i
to iterate over the array, reducing the number of times arr.length
needs to be accessed.The caching approaches aim to reduce the number of times arr.length
or other expensive operations are performed, potentially improving performance.
Now, let's analyze the results:
For loop, cached (outside)
and While loop, cached
.i
(either inside or outside the loop) outperform the ones that don't use caching.In general, caching can be an effective way to improve performance in JavaScript by reducing the number of times expensive operations are performed. However, it's essential to note that the impact of caching will depend on the specific use case and implementation details.
To summarize:
i
(either inside or outside) tends to be faster than not using caching at all.arr.length
.