var array = new Array(100);
let n = array.length;
for (let i = 0; i < n; ++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 | 27379612.0 Ops/sec |
Foreach | 13874883.0 Ops/sec |
Do While | 17427592.0 Ops/sec |
While | 27500722.0 Ops/sec |
Overview of the Benchmark
MeasureThat.net is a website that allows users to create and run JavaScript microbenchmarks. The provided benchmark compares the performance of four different looping constructs: for
, foreach
, do-while
, and while
(version 3). Each test case measures how many executions per second are possible.
Test Cases
The benchmark consists of four individual test cases:
for
loop, incrementing the index i
.forEach
method to iterate over the array, with each iteration accessing the element at index i
.i
is less than 100.i
is less than 100, but uses a different syntax.Options Compared
The benchmark compares the performance of these four looping constructs:
for
loop with manual index increment.forEach
method to iterate over an array.while
loop, but uses version 3 syntax.Pros and Cons of Each Approach
Here's a brief overview of the pros and cons of each approach:
forEach
method.while
loops, as it can start from any index. Cons: Can be less efficient due to the need to manually increment the index.while
loops.Libraries and Special Features
The benchmark uses the following libraries:
No special JavaScript features or syntax are used in this benchmark. All examples are standard, compliant JavaScript code.
Other Alternatives
For those interested in exploring alternative looping constructs or optimizations, here are some options:
forEach
, consider creating an iterator function to iterate over the array.and
Array.prototype.some: For loops that use these methods can be more efficient than traditional
for` loops.Keep in mind that optimizations may depend on specific requirements and use cases. MeasureThat.net's benchmark provides a good starting point for exploring performance differences between different looping constructs, but be sure to test your own scenarios for optimal results.