var obj = new Object()
var keys = (new Array(100)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
for (var key in obj) {
if (obj.hasOwnProperty(key)) console.log(obj[key])
}
Object.keys(obj).forEach(key => console.log(obj[key]))
for (let i = 0, keys = Object.keys(obj); i < keys.length; i++) {
console.log(obj[keys[i]]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object keys forEach | |
Object keys For loop |
Test name | Executions per second |
---|---|
For In | 2719.5 Ops/sec |
Object keys forEach | 2593.2 Ops/sec |
Object keys For loop | 2930.7 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
Benchmark Definition
The benchmark defines three test cases that compare different approaches to iterate over an object's properties:
for...in
loop to iterate over the object's properties.for
loop with an array of property names obtained from Object.keys()
.forEach()
method on the array of property names.Options Compared
The benchmark compares the performance of these three approaches:
obj.hasOwnProperty(key)
).Object.keys()
. The loop uses an index to access each property value.Pros and Cons
Here are some pros and cons for each approach:
obj.hasOwnProperty(key)
).forEach()
and its callback function.Library and Special JS Features
The benchmark uses no external libraries or special JavaScript features besides the standard ones (e.g., Object.keys()
, forEach()
).
Other Considerations
When choosing an iteration approach, consider the following factors:
for
loop with manual property iteration might be beneficial.For In
and Object keys For loop
approaches can lead to more complex code due to the need to manage indices and checks for ownership.Alternatives
If you're looking for alternative iteration approaches, consider:
Keep in mind that the choice of iteration approach ultimately depends on your specific use case, performance requirements, and personal preference.