arr = [];
arr.length = 800000;
arr.fill(0)
let sum = 0;
for (let i = 0; i < arr.length; i++) {
sum += arr[i];
}
let sum = 0;
arr.forEach(value => sum += value);
let sum = 0;
for (let i in arr) {
sum += i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
forEach | |
for...in |
Test name | Executions per second |
---|---|
for | 3.2 Ops/sec |
forEach | 91.3 Ops/sec |
for...in | 4.7 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Definition
The benchmark is designed to compare the performance of three different approaches for iterating over an array in JavaScript:
for
loopforEach
method (which is a part of the Array prototype)for...in
loopScript Preparation Code
The script preparation code initializes an empty array arr
with a length of 800,000 and fills it with zeros.
Html Preparation Code
There is no HTML preparation code provided.
Test Cases
There are three test cases:
for
loop that iterates over the array arr
, adding each element to a running sum.forEach
method to iterate over the array.for...in
loop that iterates over the array's own enumerable properties (i.e., its elements), adding each property value to a running sum.Options Compared
The benchmark compares the performance of these three approaches in terms of:
Pros and Cons
for
loop: This is a simple, straightforward approach that can be easily understood by many developers. However, it may not be as efficient as other options since it uses a fixed index i
.forEach
method: This is a part of the Array prototype, which makes it easy to use and understand for developers familiar with JavaScript arrays. It's also relatively efficient, as it avoids the need for manual indexing.for...in
loop: This approach can be confusing for some developers since it iterates over the array's own properties (not its elements). However, it may not be as efficient as forEach
, as it can involve additional overhead due to property lookup.Library and Special JS Feature
None of these test cases rely on any specific JavaScript library or special feature. They only use built-in JavaScript functionality.
Other Alternatives
Some alternative approaches that could be tested in a similar benchmark include:
reduce()
method(arr, sum) => sum += arr[i]
)for (...i of arr) {...}
)while
loop)Keep in mind that the choice of alternatives will depend on the specific goals and requirements of the benchmark.
Device Platform
The latest benchmark results indicate that Chrome 85 running on a Windows Desktop is used for these tests.