var array = new Array(100);
let arrLen = array.length
for (var i = 0; i < arrLen; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
array.some(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 65111.7 Ops/sec |
foreach | 2024463.2 Ops/sec |
some | 2481106.0 Ops/sec |
for..of | 71250.9 Ops/sec |
Let's break down what's being tested in the provided JSON benchmark.
Script Preparation Code
The script preparation code is var array = new Array(100);
, which creates an array of 100 elements. This will be the input for our loop benchmarks.
Html Preparation Code There is no HTML preparation code provided, so we can assume that this benchmark is running in a JavaScript-only environment.
Benchmark Definition The benchmark definition compares the performance of four different loops:
for
loop: let arrLen = array.length; for (var i = 0; i < arrLen; i++) { array[i]; }
forEach
loop: array.forEach(function(i) { array[i]; });
some
loop: array.some(function(i) { array[i]; });
for..of
loop: for (var i of array) { array[i]; }
Options Compared The benchmark is comparing the performance of each loop in terms of the number of executions per second.
Pros and Cons
for
loop because it eliminates the need for manual indexing.for...of
syntax. It's faster than traditional loops because it eliminates the need for manual indexing.Library Used
The benchmark is not using any external libraries, but it does use built-in JavaScript features like forEach
, some
, and for...of
.
Special JS Feature or Syntax The benchmark uses some specialized JavaScript features, including:
let
declarations (introduced in ECMAScript 2015)var
keyword with a non-strict mode (var i = 0;
)for...of
loop syntax (introduced in ECMAScript 2015)Other Alternatives If you're interested in exploring other alternatives, here are a few options:
Keep in mind that the choice of loop type ultimately depends on your specific use case, performance requirements, and personal preference.