var array = new Array(10000);
for (let i = 0; i < array.length; i++) {
array[i] = i;
}
let sum = 0;
for (var i = 0; i < array.length; i++) {
sum += array[i];
}
let sum = 0;
for (var item in array) {
sum += item;
}
let sum = 0;
array.forEach(function(item, index) {
sum += item;
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for | |
for each | |
forEach |
Test name | Executions per second |
---|---|
for | 646.7 Ops/sec |
for each | 3625.4 Ops/sec |
forEach | 24672.5 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark measures the performance of three different ways to calculate the sum of an array in JavaScript: using a traditional for
loop, for...in
, and forEach
. The test is designed to compare the performance of these approaches on a large array (10,000 elements).
Script Preparation Code
Before running the benchmarks, the script prepares an empty array with 10,000 elements and initializes its elements with their indices.
Html Preparation Code
The HTML preparation code is empty, which means that the benchmark is not dependent on any external factors like page loading or network latency.
Test Cases
There are three test cases:
for
: This test uses a traditional for
loop to iterate over the array and sum its elements.for each
: This test uses the for...in
syntax to iterate over the array's properties (which correspond to its indices) and sum them up.forEach
: This test uses the Array.prototype.forEach()
method, which is a callback-based iteration method, to iterate over the array and sum its elements.Pros and Cons of Each Approach
Here are some pros and cons for each approach:
for
: Pros:forEach
.for each
: Pros:for
loops.forEach
: Pros:Library: Lodash
In one of the benchmark test cases, for each
uses Lodash's _.each()
method, which is not explicitly mentioned in the benchmark definition. Lodash is a popular JavaScript library that provides a set of utility functions for tasks like array iteration, string manipulation, and more. In this case, it's used as an external dependency to simplify the code and focus on the performance comparison.
Other Considerations
When writing benchmarks, consider the following:
Other Alternatives
If you want to explore alternative iteration methods, consider:
Array.prototype.map()
with a callback functionfor
loop (e.g., let i = 0; array[i++];
)reduce()
method (not shown in this benchmark)Keep in mind that each approach has its own trade-offs, and you should choose the one that best fits your specific use case.