<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,i) {
if (v.a != null) {
count++;
}
})
var count = 0;
for (var i = 0; i < valArr.length; i++) {
if (valArr[i].a != null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 2571.7 Ops/sec |
native | 217.9 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, along with the pros and cons of each approach.
Benchmark Overview
The benchmark compares two approaches to iterate over an array: _.forEach
(using Lodash) and a traditional for
loop (native
). The test case uses a predefined JavaScript script that generates an array of 20,000 objects with three properties each. The goal is to count the number of objects where the a
property is not null.
Lodash .forEach
Approach
The first test case uses Lodash's _.forEach
method, which iterates over the array and calls a callback function for each element. In this implementation, the callback function checks if the a
property of each object is not null and increments a counter if it's true.
Pros:
Cons:
Traditional for
Loop (native
) Approach
The second test case uses a traditional for
loop to iterate over the array. The loop iterates 20,000 times, checking each object's a
property and incrementing a counter if it's not null.
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks like array manipulation, object creation, and more. In this case, _.forEach
is used as a convenience function to simplify iteration over arrays.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
For iterative approaches, other alternatives could include:
_.forEach
.For non-iterative approaches, other alternatives could include:
map()
function can be used to create a new array with transformed values.These alternatives may have different trade-offs in terms of performance, readability, and conciseness.