<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var values = [{
a: 30310
}, {
b: 100303
}, {
c: 3040494
}]
var valArr = [];
for (let i = 0; i < 20000; i++) {
valArr.push({
a: 1,
b: 2,
c: 3
});
}
var count = 0;
_.forEach(valArr, function(v) {
if (v.a != null) {
count++;
}
})
var count = 0;
for (let v of valArr) {
if (v.a != null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 2597.3 Ops/sec |
native | 23565.8 Ops/sec |
Let's break down the provided JSON and explain what is tested, compared options, pros and cons of each approach, and other considerations.
Benchmark Definition
The benchmark definition consists of two parts: Script Preparation Code
and Html Preparation Code
. The Script Preparation Code
defines a JavaScript array valArr
with 20,000 elements and an empty array valArr
to be iterated over. It also initializes a counter variable count
.
The Html Preparation Code
includes the URL of the Lodash library, which is used in one of the benchmark test cases.
Individual Test Cases
There are two individual test cases:
_
(underscore) object from the Lodash library to iterate over the valArr
array using the forEach
method. The code increments a counter variable count
whenever an element's property a
is not null.for...of
loop to iterate over the valArr
array, incrementing the same counter variable count
as in the Lodash forEach
test case.Comparison
The two test cases compare the performance of using a library (Lodash
) versus a native JavaScript implementation (Native
). The Lodash forEach
method is expected to be slower than the native for...of
loop due to the overhead of calling a function for each iteration, whereas the native approach avoids this overhead.
Pros and Cons
Other Considerations
Alternatives
Other approaches to iterating over arrays in JavaScript include:
forEach
, but without the need for an external library.map()
and every()
can provide a more efficient way to iterate over arrays, especially when filtering or transforming data.while
or do-while
statements can be an alternative to the native for...of
approach.In summary, the benchmark highlights the trade-offs between using external libraries and native JavaScript implementation for array iteration. While Lodash's forEach
provides a concise way to iterate over arrays, it may come at the cost of performance due to function call overhead. The native for...of
loop, on the other hand, offers faster execution but requires manual loop logic and no external library dependency.