var a = [Array(10000).keys()];
var sum = 0;
a.forEach(i => sum += i)
for (const i of a) {
sum += i;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
.forEach | |
for const of |
Test name | Executions per second |
---|---|
.forEach | 582.7 Ops/sec |
for const of | 660.7 Ops/sec |
Let's dive into the provided benchmark and explain what's being tested.
Benchmark Definition
The provided JSON defines two benchmark tests: .forEach
and for const of
. These are both used to iterate over an array, but they use different approaches to achieve this.
Options Compared
The two options being compared are:
.forEach
: This method iterates over the elements of an array using a callback function. The callback function is called for each element in the array, and it receives the current element as an argument.for const of
: This is a newer syntax introduced in ECMAScript 2017 (ES7). It uses a for...of
loop to iterate over an iterable object (such as an array) without exposing its internal implementation details.Pros and Cons
Both approaches have their advantages and disadvantages:
.forEach
:for const of
, as it creates a new scope for each iteration, which can lead to increased memory usage.for const of
:Library Usage
There is no library used in this benchmark.
Special JS Features/Syntax
The for const of
syntax uses the for...of
loop, which was introduced in ECMAScript 2017 (ES7). This syntax allows you to iterate over an array without exposing its internal implementation details. It's a more modern and efficient way of iterating over arrays compared to the traditional .forEach
method.
Other Alternatives
If you're interested in exploring other alternatives for iterating over arrays, here are a few:
for...in
: This loop iterates over an object's properties using their keys.map()
, filter()
, and reduce()
: These methods are used to transform or filter arrays without iterating over them directly.In conclusion, the provided benchmark compares two approaches for iterating over arrays: .forEach
and for const of
. The for const of
syntax is a more modern and efficient way of iterating over arrays, but it requires modern JavaScript engines to execute.