<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js"></script>
var obj = Array.from({ length: 10000 }).map((value, i) => i).reduce((val, v) => { val[v] = v; return val; }, {})
_.each(obj, function(v, k) {})
_.map(obj, function(v, k) {})
Object.entries(obj).map(function([k, v]) {})
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) { const [k, v] = entries[i]; }
_.forEach(obj, function(v, k) {})
const entries = Object.values(obj);
for (let i = 0; i < entries.length; i++) { const v = entries[i]; }
const entries = Object.keys(obj);
for (let i = 0; i < entries.length; i++) { const [k, v] = entries[i]; }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.each | |
lodash.map | |
Object.entries.map | |
vanilla for-loop w/ Object.entries | |
lodash.forEach | |
Object.values | |
Object.keys |
Test name | Executions per second |
---|---|
lodash.each | 10191.3 Ops/sec |
lodash.map | 6423.3 Ops/sec |
Object.entries.map | 3607.8 Ops/sec |
vanilla for-loop w/ Object.entries | 4148.5 Ops/sec |
lodash.forEach | 10237.8 Ops/sec |
Object.values | 32855.1 Ops/sec |
Object.keys | 6239.7 Ops/sec |
Let's dive into the details of what's being tested in this benchmark.
Benchmark Overview
The benchmark compares the performance of four ways to iterate over an object: Lodash's each
, map
, and forEach
functions, as well as three vanilla JavaScript approaches using Object.entries
, Object.keys
, and a custom for-loop with Object.entries
. The test case uses a large array-like object created from 10,000 elements.
Options Compared
The benchmark compares the following options:
_each
function to iterate over the object.entries
property of the object using a for-loop.keys
property of the object, which returns an array-like object containing the keys as strings. This approach requires additional work to access the values.map
function on the result of calling Object.entries
, which creates a new array with transformed entries._map
function to iterate over the object and create a new array with transformed values.Pros and Cons
Here are some pros and cons for each approach:
Object.entries
if the keys are small strings, as lookups are more efficient in this case.Object.entries map
, but without the need to create an intermediate result.Library Use
The benchmark uses Lodash version 4.17.5 for its functions (each
, map
, and forEach
).
Special JS Features or Syntax
None of the test cases use any special JavaScript features or syntax that would affect their performance in a significant way. The focus is on comparing the basic iteration approaches.
Alternatives
Other alternatives to these approaches include:
for...of
loops, which can be more concise and expressive than traditional for-loops.Promise.all()
or reduce()
, which can offer performance benefits in specific scenarios.Keep in mind that the choice of approach often depends on the specific requirements and constraints of a particular use case.