var arr = [];
for (var i = 0; i < 50000; i++) {
arr[i] = i;
}
let i = 0
while(i < arr.length) {
arr[i]
i++
}
for(let i = 0; i < arr.length; i++) {
arr[i]
}
let i = 0
do {
arr[i]
i++
} while(i < arr.length)
arr.forEach((data) => {
data
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
while loop | |
for loop | |
do .. while loop | |
forEach loop |
Test name | Executions per second |
---|---|
while loop | 28426.3 Ops/sec |
for loop | 33236.5 Ops/sec |
do .. while loop | 26654.0 Ops/sec |
forEach loop | 5206.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and the pros and cons of each approach.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmarking test case on MeasureThat.net. The test measures the execution speed of different looping constructs in JavaScript: while
, for
, do-while
, and forEach
.
Script Preparation Code
The script preparation code is the same for all test cases:
var arr = [];
for (var i = 0; i < 50000; i++) {
arr[i] = i;
}
This code initializes an array arr
with 50,000 elements and assigns each element its index value.
Html Preparation Code
The html preparation code is empty for all test cases, which means that no HTML-related setup or teardown is performed before running the benchmark.
Looping Constructs
Each test case measures a different looping construct:
while
loop:let i = 0;
while (i < arr.length) {
arr[i];
i++;
}
for
loop:for (let i = 0; i < arr.length; i++) {
arr[i];
}
do-while
loop:let i = 0;
do {
arr[i];
i++;
} while (i < arr.length);
forEach
loop:arr.forEach((data) => {
data;
});
Comparison of Looping Constructs
The pros and cons of each looping construct are as follows:
while
loop:for
loop:while
loops, allows for more control over the loop iteration.while
loops, requires explicit initialization of the loop variables.do-while
loop:while
loops but with an additional check at the end of each iteration.forEach
loop:Library Usage
None of the test cases use any external libraries or dependencies. The looping constructs are used in isolation to compare their execution speeds.
Special JS Features/ Syntax
None of the test cases explicitly use special JavaScript features like async/await, generators, or decorators. However, the for...of
loop (not shown in this example) is not mentioned either.
Alternative Approaches
Other alternatives for implementing looping constructs in JavaScript include:
Array.prototype.map()
, Array.prototype.filter()
, and other array methods to achieve similar results.Keep in mind that this is a simplified example, and real-world benchmarking scenarios may involve additional complexity and nuance.