var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(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 | 3485926.0 Ops/sec |
Foreach | 5718323.5 Ops/sec |
Do While | 5500375.5 Ops/sec |
While | 5587303.5 Ops/sec |
Measuring the performance of different loop constructs in JavaScript is an essential aspect of understanding how to optimize code for various browsers and devices.
What is being tested: The provided benchmark measures the execution time of four loop constructs:
for
loopforEach
loop (part of the ECMAScript standard)do-while
loopwhile
loopThese loops are used to iterate over an array and perform some operation on each element.
Options compared: The benchmark compares the execution time of these four loop constructs on a specific input:
Pros and Cons of different approaches:
for
loop with an initial counter value. It's designed to allow for more flexibility when initializing the loop counter. However, its syntax can make it harder to understand for new developers.for
loops.Library usage: None of the individual test cases use any external libraries or frameworks, as they are designed to demonstrate basic JavaScript execution performance.
Special JS feature/syntax:
The benchmark makes no specific claims about using modern JavaScript features like async/await
, Promises, or Web Workers, as these features are not essential to the fundamental nature of loop execution time comparisons.
Other alternatives:
If you're interested in exploring alternative loop constructs or optimizing your code for better performance:
yield
statements.async/await
can be used in conjunction with promises or callbacks to simplify I/O-bound operations and improve performance.In summary, this benchmark provides a straightforward comparison of the execution time of different loop constructs in JavaScript. The results help developers choose the most efficient construct for their specific use cases.