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)
}
}
}
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 | 648912.6 Ops/sec |
for each | 709773.3 Ops/sec |
I'd be happy to help you understand the JavaScript microbenchmark test case on MeasureThat.net.
What is being tested?
The benchmark is comparing two approaches: for...of
loop and the traditional forEach
method, specifically in the context of iterating over an array and checking if a specific value (in this case, 2) exists within it. The goal is to determine which approach performs better.
Options compared:
of
keyword.forEach
method: This is an older, more traditional way of iterating over arrays using a callback function.Pros and Cons:
for...of
forEach
method:Library/Function used:
In this benchmark, neither of the loop methods uses a library or external function. The focus is on comparing the performance of the two loop approaches itself.
Special JS feature/syntax:
There are no special JavaScript features or syntaxes being tested in this benchmark. It's purely focused on comparing the performance of two common loop constructs.
Other alternatives:
If you were to modify this benchmark, alternative loop methods could be compared, such as:
while
loopfor
loop with an index variableHowever, these alternatives might not provide a direct comparison to the for...of
and forEach
methods, so they might not be suitable for this specific benchmark.
Benchmark preparation code:
The provided script preparation code creates an array arr1
with three nested arrays, which is used as input for both loop methods. The HTML preparation code is empty, indicating that no HTML-related setup is needed for this benchmark.
In summary, this benchmark compares the performance of two common JavaScript loop approaches: for...of
and traditional forEach
. While there are some pros and cons to each approach, the for...of
method tends to be more readable and concise, but may not work in older environments.