var array = new Array(100000);
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];
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
some | |
for..of |
Test name | Executions per second |
---|---|
for | 5277.5 Ops/sec |
foreach | 5367.4 Ops/sec |
some | 4924.2 Ops/sec |
for..of | 692.7 Ops/sec |
Let's dive into explaining the JavaScript microbenchmark, MeasureThat.net.
What is being tested?
MeasureThat.net is comparing the performance of four different loop constructs:
for
loop (var i = 0; i < array.length; i++)
forEach
method (array.forEach(function(i) { ... })
)some
method (array.some(function(i) { ... })
)for...of
loop (for (var i of array) { ... }
)These loops are designed to iterate over an array and execute a block of code for each element.
Options being compared
The comparison focuses on the execution speed of these four loop constructs. Each test case measures how many times a given browser instance executes the loop body within a second, which is represented by ExecutionsPerSecond
value in the benchmark results.
Pros and Cons of different approaches:
for
loop: This is a straightforward loop construct that can be easily understood and optimized for performance. However, it requires manual indexing (array[i]
) which might lead to issues if the array index is not properly managed.forEach
method: The forEach
method provides an elegant way to iterate over arrays, but its performance can be slower due to additional overhead (e.g., checking for null elements). Additionally, it does not provide direct access to the iteration index.some
method: The some
method is similar to forEach
, but it only executes when at least one element matches the condition. This might lead to more iterations in some cases, affecting performance.for...of
loop: The for...of
loop provides a concise way to iterate over arrays and objects without manual indexing or using indices. However, its performance is not as well-understood as other loops, and it may have additional overhead.Libraries and their purpose
None of the individual test cases rely on any external libraries beyond what's typically included in modern JavaScript environments (e.g., Array.prototype.forEach()
).
Special JS features or syntax:
The only notable feature being tested is the use of for...of
loop, which allows iterating over arrays without manual indexing. This construct was introduced in ECMAScript 2015 and provides a more concise way to iterate over arrays.
Other alternatives:
array[i]
) can also be used with for
or forEach
.map()
and reduce()
methods: Instead of using individual loops for each element, you could use map()
and reduce()
to achieve similar results.Keep in mind that the specific choice of loop construct or optimization technique ultimately depends on the particular use case and requirements.