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));
for(let [key,value] of Object.entries(obj)){
console.log(value);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys forEach | |
Object entries forEach | |
object values forEach | |
for of Object.entries |
Test name | Executions per second |
---|---|
For In | 71.2 Ops/sec |
Object values | 69.8 Ops/sec |
Object keys forEach | 72.6 Ops/sec |
Object entries forEach | 54.9 Ops/sec |
object values forEach | 73.8 Ops/sec |
for of Object.entries | 65.3 Ops/sec |
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark, specifically measuring the performance of different iteration methods in a JavaScript context. The benchmark compares the execution time of four approaches:
for...in
loop.Object.values()
method followed by a forEach()
loop.Object.keys()
method followed by a forEach()
loop.for...of
loop followed by a forEach()
call on the result of Object.entries()
.Option Comparison
Here's a brief overview of each option:
For...in: This is one of the most common ways to iterate over an object in JavaScript. It has some drawbacks, however:
Object.values() and forEach(): This combination is often used when you need to process only the object's own values. However:
Object.values()
), they won't be included in this iteration.Object.keys().forEach(): Similar to the previous option but iterates over property names:
For...of and Object.entries().forEach(): This pair is particularly interesting because it leverages modern JavaScript features for efficient iteration. It does, however, have some limitations:
Object.entries()
to iterate.Object.entries()
) or other unexpected properties, they will be skipped.Pros and Cons
Other Considerations
When choosing an iteration method, consider the following:
For this specific benchmark, it appears the modern approaches (Object.values() + forEach(), Object.keys().forEach()) outperform the older method (for...in), possibly due to their ability to iterate more predictably over property names or values. The comparison for using Object.entries().forEach() and For...of shows its potential as a modern approach but depends on specific requirements.
Alternatives
Other alternatives that may be worth considering:
However, considering the specific nature of this benchmark and its focus on direct property access/iteration (rather than filtering, mapping, or transforming data), sticking with the original methods seems most relevant.