x = [1,2,3,4,5]
y = []
x.forEach(i => y.push(i))
y = []
for (const i of x) {
y.push(i)
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
for ... of |
Test name | Executions per second |
---|---|
forEach | 16383338.0 Ops/sec |
for ... of | 12767566.0 Ops/sec |
Let's dive into the JavaScript microbenchmark on MeasureThat.net.
The provided JSON represents two test cases, comparing the performance of forEach
and for...of
loops in JavaScript. Both tests aim to push elements from an array onto another array.
What is tested?
In essence, both tests are measuring how fast it is to iterate through an array and add each element to a new array. The main difference between the two approaches lies in the way the iteration is performed:
forEach
loop: This method iterates over the array using a callback function, where each element is passed as an argument (i
in this case). The callback function can perform any operation on i
.for...of
loop: This approach uses a for-of loop to iterate directly over the elements of the array.Options compared
The main comparison is between these two iteration methods:
forEach
:for...of
due to the overhead of function calls and argument passing.for...of
:Library usage
None of the provided benchmark test cases uses any external libraries. However, MeasureThat.net may employ internal optimizations or implementation details that are not visible in these test cases.
Special JavaScript feature or syntax
The tests explicitly use the for...of
loop, which is a modern JavaScript feature introduced in ECMAScript 2015 (ES6). This allows for more readable and concise iteration over arrays.
Other alternatives
When compared to other iteration methods like traditional for
loops with indexes (x.forEach(i => y.push(i))
is not used here), the choice between forEach
and for...of
often comes down to:
forEach
method, it might be a better choice for simple iterations.for...of
will generally provide a slight performance boost.forEach
should be weighed against potential performance trade-offs.In summary, both tests compare the performance of two commonly used iteration methods in JavaScript. While for...of
tends to offer slightly better performance, the choice between these approaches ultimately depends on your specific use case and personal preference.