<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var values = [{a: 30310}, {b: 100303}, {c: 3040494}]
var count = 0;
_.forEach(values, function(v,i) {
if (v.a != null) {
count++;
}
})
var count = 0;
for (let v of values) {
if (v.a !== null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 2895822.8 Ops/sec |
native | 10442179.0 Ops/sec |
I'd be happy to help you understand the JavaScript microbenchmark on MeasureThat.net.
Benchmark Overview
The benchmark compares the performance of two approaches: using _.forEach()
from the Lodash library and using a traditional for
loop (also known as a "native" loop). The goal is to measure which approach is faster for iterating over an array of objects.
Lodash _.forEach() Approach
_.forEach()
function is used to iterate over the values
array. The callback function passed to _.forEach()
increments a counter (count
) whenever it encounters an object with a non-null value on the a
property.Native Approach
for
loop to iterate over the values
array. Inside the loop, the code checks if each object has a non-null value on the a
property and increments a counter (count
) if true._.forEach()
Special JavaScript Features/Syntax
None mentioned in the provided benchmark.
Other Alternatives
Besides the two approaches shown, other alternatives could be:
Array.prototype.forEach()
: This is another built-in method for iterating over an array. While similar to Lodash's _.forEach()
function, it might have different performance characteristics due to its implementation.for
loop with an index variable: Similar to the native approach, this would involve manually incrementing an index variable and checking the value of each object on the array.Benchmark Results
The latest benchmark results show that:
_.forEach()
function, with a higher number of executions per second.Keep in mind that these results might vary depending on the specific test environment and system configuration.