const arr = new Array(10000);
for (var i = 0; i < arr.length; i++) {
var a = arr[i]
}
const arr = new Array(10000);
for (var i = arr.length; i >= 0; i--) {
var a = arr[i]
}
const arr = new Array(10000);
var i = arr.length
while (i--) {
var a = arr[i]
}
const arr = new Array(10000);
arr.forEach(v => {
var a = v
});
const arr = new Array(10000);
arr.every(v => {
var a = v
return true
});
const arr = new Array(10000);
for (var v in arr) {
var a = v
}
const arr = new Array(10000);
for(var v of arr) {
var a = v
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
use basic for | |
use basic for (start at last) | |
use while (start at last) | |
use forEach | |
use every | |
use for...in | |
use for...of |
Test name | Executions per second |
---|---|
use basic for | 102308.3 Ops/sec |
use basic for (start at last) | 102653.6 Ops/sec |
use while (start at last) | 43610.0 Ops/sec |
use forEach | 4082.8 Ops/sec |
use every | 5982.5 Ops/sec |
use for...in | 193343.4 Ops/sec |
use for...of | 21995.6 Ops/sec |
Let's break down the benchmark and its various components.
Benchmark Definition JSON
The provided JSON represents a JavaScript microbenchmark that tests the performance of different array iteration methods. The Benchmark Definition
section outlines the specific test case:
const arr = new Array(10000);
: Creates an array with 10,000 elements.for (var i = 0; i < arr.length; i++) { ... }
)for (var i = arr.length; i >= 0; i--) { ... }
)while (i--) { ... }
)forEach
method (arr.forEach(v => { var a = v; });
)every
method (arr.every(v => { var a = v; return true; });
)for(var v in arr) { var a = v; }
)for (var v of arr) { var a = v; }
)Options Comparison
The six options are compared to measure their performance:
i
variable to iterate over the array elements.i--
) to access each element.true
if all elements pass the provided test function; otherwise, it returns false
. The loop is not strictly necessary in this case.Pros and Cons of Each Approach
Here's a brief summary:
true
or false
, which might not always match the expected behavior.Performance Insights
The benchmark results show that the performance of each approach varies depending on the specific use case:
forEach
, every
, and For...of loops often outperform basic for loops, especially when considering readability and conciseness.Keep in mind that these results are specific to this particular benchmark and might not generalize to all scenarios.