arr1 = [[1,2,3],[1,2,3],[1,2,3]]
result = []
for(const arr of arr1) {
for (const num of arr) {
if (num === 2) {
result.push(num)
continue
}
}
}
result = []
arr1.forEach((arr) => {
arr.forEach((num) => {
if(num === 2) {
result.push(num)
}
})
})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for..of | |
for each |
Test name | Executions per second |
---|---|
for..of | 6256677.5 Ops/sec |
for each | 4642170.5 Ops/sec |
I'd be happy to help you understand the provided JavaScript benchmark.
What is being tested?
The benchmark compares two approaches: for..of
and forEach
. Both methods are used to iterate over an array (arr1
) and push values into an empty array (result
) if they meet a certain condition (i.e., if the value is equal to 2).
Options compared:
Two options are being compared:
for..of
: This method uses the for...of
loop syntax, which allows you to iterate over an array without explicitly indexing into it.forEach
: This method uses the forEach
method, which is a part of the Array prototype.Pros and Cons:
for..of
:for...of
loopforEach
:for...of
Library or special JS feature:
Neither of these options uses a library or a special JavaScript feature. Both methods are part of the standard JavaScript language.
Other alternatives:
If you want to explore alternative approaches, here are a few:
while
loop to iterate over the array, but this would require more manual indexing and control.reduce()
can be used to accumulate values into an array. However, it might not provide the same level of performance as the for...of
or forEach
methods.map()
, filter()
): These methods are typically used for transforming arrays or filtering out elements, but they can also be used to iterate over an array if desired.In this specific benchmark, the performance difference between for...of
and forEach
is relatively small, indicating that both approaches have similar execution times. However, further benchmarks may reveal differences in performance depending on the specific use case and environment.