<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.15/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).forEach(function([k, v]) {})
const entries = Object.entries(obj);
for (let i = 0; i < entries.length; i++) { const [k, v] = entries[i]; }
Object.keys(obj).forEach(function(k) {const v = obj[k]})
const keys = Object.keys(obj);
for (let i = 0; i < keys.length; i++) { const k = keys[i]; const v = obj[k]; }
for (const k in obj) {
const v = obj[k]
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash.each | |
lodash.map | |
Object.entries.forEach | |
vanilla for-loop w/ Object.entries | |
Object.keys.forEach | |
vanilla for-loop w/ Object.keys | |
for in |
Test name | Executions per second |
---|---|
lodash.each | 3082.9 Ops/sec |
lodash.map | 3103.2 Ops/sec |
Object.entries.forEach | 1506.1 Ops/sec |
vanilla for-loop w/ Object.entries | 1842.7 Ops/sec |
Object.keys.forEach | 848.2 Ops/sec |
vanilla for-loop w/ Object.keys | 917.2 Ops/sec |
for in | 828.9 Ops/sec |
The provided JSON represents a benchmarking test for comparing the performance of different approaches to iterate over an object in JavaScript.
Here's what's being tested:
_.each
and _.map
. Both methods are used to iterate over an array (in this case, an object) and perform some operation on each element.Object.entries.forEach
: This method iterates over the key-value pairs of an object using the entries()
method and then executes a callback function for each pair.vanilla for-loop w/ Object.keys
: This approach uses a traditional for loop with the Object.keys()
method to get an array of the object's keys, and then iterates over that array to access the corresponding values in the object.The pros and cons of these approaches are:
Lodash methods:
Pros:
Cons:
Vanilla Object iteration:
Pros:
Cons:
For-in loop:
Pros:
Cons:
Other considerations:
Object.entries.forEach
and for-in
were generally faster than Lodash methods.Alternatives:
forEach()
on the object itself (e.g., obj.forEach()
)for...of
loops