<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var values = ["a", "b", "c"]
var count = 0;
_.forEach(values, function(v,i) {
if (v != null) {
count++;
}
})
var count = 0;
for (var i = 0; i < values.length; i++) {
if (values[i] != null) {
count++;
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.forEach | |
native |
Test name | Executions per second |
---|---|
lodash.forEach | 2877903.8 Ops/sec |
native | 1699929.5 Ops/sec |
Let's dive into the world of MeasureThat.net and explore what's tested in this benchmark.
Benchmark Overview
The benchmark compares the performance of two approaches: Lodash forEach
(a popular utility library) and a native for
loop, against an array of values ("a"
, "b"
, "c"
).
Lodash forEach
vs Native for
Loop
Both test cases aim to iterate through the values
array and increment a counter (count
) for each non-null element.
Here's the key difference:
forEach
: This method takes two arguments: an array (values
) and a callback function (which returns the current value and its index). The callback is executed for each element in the array, and it has access to the current element's value and its index.for
Loop: This is a traditional loop that uses an index variable (i
) to iterate through the array. It checks each element against null separately.Pros and Cons
forEach
:for
Loop:Library: Lodash
Lodash is a popular utility library that provides various functions for working with arrays, objects, and other data structures. In this benchmark, Lodash's forEach
method is used to iterate through the array and execute a callback function for each element.
Special JavaScript Feature/Syntax: None
There are no special JavaScript features or syntax used in these test cases. The code is standard JavaScript, with no advanced features like async/await, Promises, or Web APIs that require specific browser support.
Other Alternatives
If you're interested in exploring alternative approaches, here are a few examples:
Array.prototype.forEach()
: This is another built-in method that can be used to iterate through an array. However, its performance might vary depending on the JavaScript engine and implementation.Array.prototype.map()
with an empty function: While not exactly the same as forEach
, this approach can achieve similar results by mapping each element to a null value.for...of
loop or a recursive function.Keep in mind that these alternatives might have different performance characteristics, readability, and maintainability trade-offs.