var array = new Array(1000000);
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 | 10.0 Ops/sec |
foreach | 893.7 Ops/sec |
some | 895.0 Ops/sec |
for..of | 17.1 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Definition
The benchmark is designed to compare the performance of four different loop constructs:
for
loopforeach
loop (also known as forEach
)some
loop (note: some
is not a typical loop construct, but rather a method on arrays that returns a boolean indicating whether at least one element matches a given condition)for...of
loopLoop Constructs
Each loop construct has its own strengths and weaknesses:
for
loop: This is the most traditional loop construct in JavaScript. It allows for manual iteration using an index variable (i
). The loop runs as long as the condition is true, and it provides fine-grained control over the iteration process.foreach
loop: This loop construct is more modern and provides a simpler way to iterate over arrays. It's often preferred for its readability and conciseness.for
, and can be slower due to the overhead of function calls.some
loop: As mentioned earlier, some
is a method on arrays that returns a boolean indicating whether at least one element matches a given condition. It's not typically used for iteration, but rather for filtering or testing elements.for...of
loop: This is a more modern loop construct that provides a simpler way to iterate over arrays and other iterables. It's often preferred for its readability and conciseness.for
, and can be slower due to the overhead of iterator setup.Other Considerations
When choosing a loop construct, consider the following factors:
Library Usage
In this benchmark, all four loop constructs are used without any additional libraries. However, in real-world applications, you may encounter situations where a library is necessary to achieve specific functionality.
Special JS Features
This benchmark does not explicitly test special JavaScript features such as let
or const
, but it's worth noting that these declarations can affect variable scope and behavior.
Now, let's summarize the alternatives:
while
, do-while
, or array iteration using indexing (array[i] = value;
).Keep in mind that each loop construct has its strengths and weaknesses, and choosing the right one depends on your specific needs and priorities.