var array = new Array(100);
let arrLength = array.length;
for (var i = 0; i < arrLength; i++)
array[i];
array.forEach((i)=> array[i]);
var i = 0;
do {
array[i];
i++;
} while (i < 100);
var i = 0;
while (i < 100) {
array[i];
i++;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For | |
Foreach | |
Do While | |
While |
Test name | Executions per second |
---|---|
For | 9649582.0 Ops/sec |
Foreach | 12575770.0 Ops/sec |
Do While | 9170519.0 Ops/sec |
While | 10161368.0 Ops/sec |
The benchmark provided aims to compare the performance of four different looping methods in JavaScript when iterating over an array. The looping methods being tested are for
, forEach
, do while
, and while
loops. All iterations utilize an array of a fixed length (100) that is pre-defined in the preparation code.
For Loop:
let arrLength = array.length;
for (var i = 0; i < arrLength; i++)
array[i];
forEach
. ForEach Method:
array.forEach((i) => array[i]);
for
and while
, as the function callback adds overhead.break
or continue
to manipulate the flow of the loop.Do While Loop:
var i = 0;
do {
array[i];
i++;
} while (i < 100);
while
loop, but less commonly used.While Loop:
var i = 0;
while (i < 100) {
array[i];
i++;
}
for
, it allows fine-tuned control over the iteration.for
for indefinite loops where the exit condition isn't based solely on a counter.The results from the most recent tests show performance measured in executions per second for each method. The highest-performing method was forEach
, followed by while
, for
, and do while
. Here are the execution rates:
map
, filter
, and reduce
also exist in JavaScript, which provide similar functionality with added capabilities (like transformed outputs) but come with their own performance trade-offs.In summary, while the benchmark illustrates performance differences among loop types, choices in production code should be made with an emphasis on clarity, maintainability, and context-driven performance concerns.