var arr = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
arr.forEach((value) => { console.log(value); });
for (const value of arr) {
console.log(value);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
forEach | |
for.. of |
Test name | Executions per second |
---|---|
forEach | 35340.0 Ops/sec |
for.. of | 36579.2 Ops/sec |
Let's break down the JavaScript microbenchmarking test case provided by MeasureThat.net.
Benchmark Definition and Script Preparation Code
The benchmark is comparing two approaches for iterating over an array: for.. of
and forEach
. The script preparation code creates an array arr
with 11 elements, which will be used as input for both iteration methods.
Options being compared
The two options being compared are:
of
keyword.Pros and Cons
for.. of:
Pros:
Cons:
forEach
due to additional overhead for type checking and iteration planningforEach:
Pros:
Cons:
for.. of
Other considerations
Both for.. of
and forEach
have their strengths and weaknesses. In general, for.. of
is a better choice when:
On the other hand, forEach
might be a better choice when:
for.. of
Library usage
There is no explicit library usage in this benchmark.
Special JS feature/syntax
This benchmark does not use any special JavaScript features or syntax beyond the two iteration methods being compared. However, it's worth noting that for.. of
relies on the ES6 iteration protocol, which might introduce some complexity for developers familiar with older iteration methods.
Other alternatives
If you're interested in exploring alternative iteration methods or comparing performance between different approaches, MeasureThat.net offers a wide range of benchmarks and tools. Some examples include:
map()
, filter()
, reduce()
String.prototype.match()
, String.prototype.replace()
Feel free to explore these alternatives or create your own benchmarks using MeasureThat.net's tools!