var values = [{a: 30310}, {b: 100303}, {c: 3040494}]
var count = 0;
values.forEach((v,i) => {
if (v.a != null) {
count++;
}
})
var count = 0;
for (var i = 0; i < values.length; i++) {
if (values[i].a != null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
ES6 forEach | |
Native for loop |
Test name | Executions per second |
---|---|
ES6 forEach | 10885547.0 Ops/sec |
Native for loop | 2240797.0 Ops/sec |
Let's dive into the provided benchmark and break down what is being tested, compared, and their pros and cons.
What is being tested?
The provided benchmark compares two approaches to iterate over an array: ES6 forEach
and native for loop. The test case uses a predefined JavaScript array values
with three elements.
Options being compared:
forEach
:array.forEach(callbackFunction)
.for (var i = 0; i < array.length; i++) { ... }
.Pros and Cons of each approach:
forEach
:forEach
due to direct access to array elements.forEach
.Library usage:
There is no explicit library mentioned in the benchmark. However, it's worth noting that some JavaScript engines or browsers may have optimizations or features that affect performance, such as:
Special JS feature or syntax:
There are no special JavaScript features or syntax mentioned in the benchmark. However, if we were to extend this comparison to other approaches, some notable alternatives include:
Array.prototype.forEach.call()
: A more explicit way of calling forEach
on an array.Map.prototype.forEach()
: Similar to forEach
but designed for use with Maps (key-value pairs).for...of
loop: A newer looping construct that's similar to forEach
but can be used in different contexts.Other alternatives:
Some other approaches that could be compared include:
reduce()
instead of forEach
: This might lead to slightly different performance characteristics due to the nature of these functions.In conclusion, the provided benchmark compares two common approaches to iterate over arrays in JavaScript: ES6 forEach
and native for loops. The choice between these approaches depends on factors such as performance requirements, code readability, and personal preference.