<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js'></script>
var obj = Array.from({ length: 10000 }).map((value, i) => i);
_.each(obj, function(v) {})
obj.forEach(function(v) {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.each | |
native forEach |
Test name | Executions per second |
---|---|
lodash.each | 11829.7 Ops/sec |
native forEach | 208302.1 Ops/sec |
The benchmark defined in the provided JSON compares the performance of two different methods for iterating over arrays in JavaScript: the _.each
method from the Lodash library and the native forEach
method available on array objects.
Lodash each
Method:
_.each(obj, function(v) {})
each
method in Lodash is used to iterate over elements in a collection (array or object) and execute a function for each element.Native forEach
Method:
obj.forEach(function(v) {})
forEach
method allows iteration over each element in an array and executes a provided function once for each array element.forEach
method achieves 208,302 executions per second, while the Lodash each
method only achieves 11,829 executions per second. This indicates that the native method is significantly faster than the Lodash method in this specific benchmark scenario.each
Pros:
Cons:
forEach
Pros:
Cons:
Array.from({ length: 10000 }).map((value, i) => i)
, which is a common approach to create an array with specific values. The size of the array (10,000) ensures a substantial number of iterations for the tests.Other alternatives to the methods tested could include:
for..of
Loop: A modern iteration method that provides a syntax for iterating over iterable objects, including arrays. It offers a simpler syntax and avoids some of the pitfalls of traditional for
loops.
for (const v of obj) {
// process v
}
Traditional for
Loop: While more verbose, the traditional for
loop provides maximum control over iteration and might be more performant in certain scenarios.
for (let i = 0; i < obj.length; i++) {
const v = obj[i];
// process v
}
map
Method: If the intention is to transform each value in the array rather than just iterating through them, the map
method could be a better fit.
In summary, this benchmark is valuable for understanding the performance differences between using a utility library (Lodash) and native JavaScript methods, emphasizing the trade-offs between speed and features when selecting an approach for iterating over arrays.