var array = new Array(100);
for (var i = 0; i < array.length; i++) {
array[i];
}
array.forEach(function(i) {
array[i];
});
array.some(function(i) {
array[i];
});
for (var i of array) {
array[i];
}
var i = 0;
var len = array.length;
while(i<len)
{
array[i];
i++
}
for (const [index, element] of array.entries()){
array[index]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of | |
while | |
for..of with array.entries |
Test name | Executions per second |
---|---|
for | 64277.9 Ops/sec |
foreach | 330851.8 Ops/sec |
some | 331039.4 Ops/sec |
for..of | 85139.4 Ops/sec |
while | 126759.0 Ops/sec |
for..of with array.entries | 84609.8 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark definition is a JSON object that outlines the scope and purpose of the benchmark. In this case, it tests the performance of four different loop constructs:
for
loopsforEach
loopssome
loopsfor..of
loopsThe benchmark also includes a script preparation code (var array = new Array(100);
) and no HTML preparation code.
Options Compared
The benchmark compares the performance of four different loop constructs:
for
loop: uses an explicit counter variable (i
) to iterate over the array.forEach
loop: uses the Array.prototype.forEach()
method, which is a built-in array method that executes a callback function for each element in the array.some
loop: uses the Array.prototype.some()
method, which returns true
if at least one element in the array passes the test implemented by the provided function.for..of
loop: uses the new for...of
syntax, which is a more concise and expressive way to iterate over arrays.Pros and Cons of Each Approach
Here's a brief summary of the pros and cons of each approach:
for
loop:forEach
loop:for
loops due to method call overhead.some
loop:for
loops for certain use cases.for..of
loop:for...of
syntax, which may not be widely supported.Library and Purpose
The benchmark uses the built-in JavaScript array methods (forEach
, some
) to implement the loops. These methods are designed to optimize performance and provide a concise way to iterate over arrays.
Special JS Features or Syntax
None of the individual test cases rely on any special JavaScript features or syntax beyond what's necessary for the loops themselves (e.g., using const
for variable declarations). However, some test cases do use the new for...of
syntax (for..of
and for..of with array.entries
), which is a relatively recent addition to the language.
Alternatives
If you're interested in alternative loop constructs or optimizations, you may want to explore other benchmarking frameworks or libraries. Some examples include:
Keep in mind that each of these alternatives has its own strengths and weaknesses, and may not offer identical features or support to MeasureThat.net.