<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
var obj = new Object()
var keys = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
for (var key in obj) {
console.log(obj[key]);
}
for(let value of Object.values(obj)){
console.log(value);
}
Object.keys(obj).forEach(key => console.log(obj[key]));
Object.entries(obj).forEach(([key, value]) => console.log(key,'->',value));
Object.values(obj).forEach(value => console.log(value));
_.forEach(_.values(obj), value => console.log(value))
const arr = Object.values(obj);
for (var i=0, n=arr.length; i < n; ++i){
console.log(arr[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys forEach | |
Object entries forEach | |
object values forEach | |
_.forEach(_.values()) | |
n=arr.length |
Test name | Executions per second |
---|---|
For In | 35.8 Ops/sec |
Object values | 35.2 Ops/sec |
Object keys forEach | 40.8 Ops/sec |
Object entries forEach | 33.7 Ops/sec |
object values forEach | 43.1 Ops/sec |
_.forEach(_.values()) | 35.5 Ops/sec |
n=arr.length | 35.9 Ops/sec |
Let's break down the JavaScript microbenchmark and explain what's being tested, compared, and their pros/cons.
Benchmark Overview
The benchmark compares six different approaches to iterate over an object:
for...in
loopObject.values()
methodObject.keys()
method with forEach()
Object.entries()
method with forEach()
_.forEach(_.values())
methodWhat's being tested?
Each test case measures the performance of a specific approach to iterate over the object, which contains 10,000 properties (keys) with values from 1 to 10,000.
Comparison options
Here are the compared options:
for...in
loopObject.values()
methodObject.keys()
method with forEach()
Object.entries()
method with forEach()
_.forEach(_.values())
methodn=arr.length
)Pros and Cons of each approach
for...in
loop:Object.values()
method:Object.keys()
method with forEach()
:Object.values()
, but allows access to both keys and values.Object.values()
due to the additional overhead of iterating over property names.Object.entries()
method with forEach()
:_.forEach(_.values())
method:n=arr.length
):Other considerations
The benchmark also considers the following factors:
These factors may affect the performance of each approach, but are not directly related to the iteration logic itself.
I hope this explanation helps clarify what's being tested and compared in the JavaScript microbenchmark!