<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;
var len = values.length;
for (var i = 0; i < len; i++) {
if (values[i].a != null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 2897460.0 Ops/sec |
native | 3784559.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Definition The benchmark definition json provides us with information about the test case being measured. In this case, we have two test cases:
lodash.forEach
native
Both test cases iterate over an array of objects (values
) and count the number of objects with a non-null value for property a
. The main difference between the two test cases lies in how they achieve this iteration.
Options Compared
We have two options being compared:
_
symbol to refer to the Lodash library, which provides a utility function called forEach()
. The forEach()
function takes three arguments: the array to iterate over (values
), a callback function that will be executed for each element in the array (function(v,i) { ... }
), and an optional fourth argument (in this case, not provided).for
loop to iterate over the array.Pros and Cons of Each Approach
Pros:
Cons:
Pros:
Cons:
Library: Lodash
Lodash is a popular JavaScript library that provides a set of utility functions for common tasks, such as array manipulation, object transformation, and more. In this benchmark, the forEach()
function from Lodash is used to iterate over the values
array.
Special JS Feature/Syntax (None) There are no special JavaScript features or syntax used in this benchmark.
Other Alternatives
Other alternatives for iterating over arrays include:
Array.prototype.forEach()
: This is a built-in method of the Array prototype that can be called on an array to iterate over its elements.forEach()
with a custom callback function: You can create your own custom implementation of the forEach()
function using a recursive or iterative approach.Note that these alternatives may have similar performance characteristics to the Lodash implementation, but might not be as concise or readable.