var array = new Array(100);
for (let i = 0; i < 100; i++) {
array[i] = i * i;
}
let sum = 0
for (let i = 0, l = array.length; i < l; i++) {
sum += array[i];
}
let sum = 0;
array.forEach(function(i) {
sum += array[i];
});
let sum = 0;
for (var i in array) {
sum += array[i];
}
let sum = 0;
for (var i of array) {
sum += array[i];
}
array.reduce((a, b) => a + b, 0);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
foreach | |
for in | |
for..of | |
reduce |
Test name | Executions per second |
---|---|
for | 337955.8 Ops/sec |
foreach | 225454.9 Ops/sec |
for in | 234273.3 Ops/sec |
for..of | 236524.2 Ops/sec |
reduce | 6406056.0 Ops/sec |
Let's break down the test cases and explain what's being tested.
General Overview
The benchmark measures the performance of different loop methods in JavaScript: for
, forEach
, for...in
, for...of
, and reduce
. The test case uses an array of 100 elements, where each element is a squared value (i * i
).
Loop Methods Compared
Here's what each loop method does:
let i = 0;
) and checks if the index is within the bounds of the array.for (var i in array)
).for (var i of array)
).Pros and Cons
Here are some pros and cons for each loop method:
Library Usage
None of the loop methods use any external libraries in this benchmark.
Special JS Features or Syntax
Only For...of uses a special syntax (for (var i of array)
) that's not widely supported. However, since most modern browsers support it, its usage is still reasonable.
Other Considerations
When choosing a loop method, consider the following:
for
or reduce
might be better choices.forEach
or For...of
could be more suitable.For...in
.Alternatives
If you want to test other loop methods, consider adding:
Keep in mind that some of these alternatives might not be as efficient or readable as the original loop methods, so their usage depends on specific use cases and requirements.