var arr = [];
for (var i = 0; i < 1000; i++) {
arr[i] = i;
}
function someFn(i) {
return i * 3 * 8;
}
arr.forEach(item => someFn(item))
for (let i = 0; i < arr.length; i++) {
someFn(arr[i])
}
for (const item of arr) {
someFn(item)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
foreach | |
for | |
for_of |
Test name | Executions per second |
---|---|
foreach | 138386.6 Ops/sec |
for | 782708.9 Ops/sec |
for_of | 141272.2 Ops/sec |
What is being tested?
The provided JSON represents a JavaScript microbenchmark that compares the performance of three different loops to iterate over an array: forEach
, for
, and for...of
. The benchmark creates an array with 1000 elements, initializes each element with its index multiplied by a specific formula (i * 3 * 8
), and then defines a function someFn
that performs the same calculation.
Options compared
The three loops being compared are:
forEach
: This loop uses the Array.prototype.forEach()
method to iterate over the array, which calls the provided callback function once for each element in the array.for
: This loop uses a traditional for
loop with an index variable (i
) to iterate over the array elements.for...of
: This loop uses the for...of
loop syntax to iterate over the array elements, which is a newer feature introduced in ECMAScript 2015.Pros and Cons of each approach
forEach()
method callforEach
push()
or splice()
)forEach
Library
None of the provided loops rely on a specific library.
Special JS features or syntax
The for...of
loop uses the new for...of
loop syntax, which is a feature introduced in ECMAScript 2015. This syntax allows for more concise and expressive iteration over arrays, objects, and other iterable data structures.
Other alternatives
If you're interested in exploring alternative approaches to iterating over arrays, you might consider using:
map()
: A method that applies a transformation function to each element of an array and returns a new array with the results.reduce()
: A method that reduces an array by applying a reduction function to each element and accumulating a result.Array.prototype.forEach()
or other methods.These alternatives may have different performance characteristics, use cases, and code readability compared to the traditional loops being compared in this benchmark.