<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var value = [{a: 30310}, {b: 100303}, {c: 3040494}]
_.each(value, function(v,i) {})
value.forEach(function(v,i) {})
_.forEach(value, function(v,i) {})
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.each | |
native | |
lodash.forEach |
Test name | Executions per second |
---|---|
lodash.each | 14263258.0 Ops/sec |
native | 98018536.0 Ops/sec |
lodash.forEach | 12119508.0 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares three approaches for iterating over an array: native forEach
, lodash.each
, and lodash.forEach
. The test case uses a predefined value array with 3 elements, each containing a different property (a, b, c) with varying values.
Options Compared
forEach
: This is the built-in JavaScript method for iterating over an array. It takes two arguments: a callback function and an optional thisArg.lodash.each
: A utility function from the Lodash library that iterates over an object (or array) and calls a provided callback function on each element.lodash.forEach
: Another utility function from Lodash, similar to each
, but designed for arrays instead of objects.Pros and Cons
forEach
:lodash.each
:lodash.forEach
:each
, but optimized for arrays, making it potentially faster than each
.each
, requires importing Lodash library.Library and Purpose
Lodash is a popular JavaScript utility library that provides various functions for tasks like array manipulation, object transformation, and more. In this benchmark, the two relevant functions are used to iterate over arrays:
lodash.each
: Iterates over an object (or array) and calls a callback function on each element.lodash.forEach
: Iterates over an array and calls a callback function on each element.Special JS Features or Syntax
None mentioned in this benchmark. However, it's worth noting that some modern JavaScript features like async/await, generators, and iterators might affect the execution of these methods.
Other Alternatives
If you want to explore other alternatives for iterating over arrays, here are a few options:
Array.prototype.forEach()
: The built-in method is often used in conjunction with the forEach
property on an array.for...of
loop: A modern approach to looping through arrays using a for loop with the of keyword.map()
, filter()
, and reduce()
methods: These methods can be used to transform, filter, or reduce an array, but may not provide the same level of iteration as forEach
.Keep in mind that each approach has its trade-offs in terms of readability, performance, and ease of use. The choice ultimately depends on your specific requirements and coding style preferences.