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));
let values = Object.values(obj)
let length = values.length
for(let i = 0; i < length; i++){
console.log(values[i]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys forEach | |
Object entries forEach | |
object values forEach | |
Object entries plus for loop |
Test name | Executions per second |
---|---|
For In | 18.5 Ops/sec |
Object values | 18.4 Ops/sec |
Object keys forEach | 20.1 Ops/sec |
Object entries forEach | 15.1 Ops/sec |
object values forEach | 21.3 Ops/sec |
Object entries plus for loop | 19.8 Ops/sec |
Let's break down the JavaScript microbenchmark and analyze what is being tested.
Benchmark Definition
The benchmark definition specifies that we are comparing different approaches to iterate over an object's properties:
for (var key in obj)
to iterate over the object's own enumerable properties.for(let value of Object.values(obj))
to iterate over the object's values as an array.Object.keys(obj).forEach(key => console.log(obj[key]))
to iterate over the object's keys as an array using forEach
.Object.entries(obj).forEach(([key, value]) => console.log(key,'->',value))
to iterate over the object's key-value pairs as an array of tuples using forEach
.Object.values(obj)
to iterate over the object's values.Options Comparison
The options being compared are:
in
operator.forEach
. This approach is similar to Object.values
, but with a different data structure.forEach
. This approach provides direct access to both keys and values.Pros and Cons
Here are some pros and cons for each approach:
in
operator.Object.entries
. The forEach
approach can be more efficient than a custom loop with Object.values
.forEach
approach can be more efficient than a custom loop with Object.values
.Other Considerations
When choosing an iteration approach, consider the following factors:
Object.values
, Object.keys
and forEach
) are generally more efficient than those using objects with in
.For In
can be more intuitive for simple use cases, while object iteration approaches using arrays might require additional consideration for readability.Object.entries
or Object.keys
and forEach
provide this.Library Use
The benchmark uses the following libraries:
No special JavaScript features or syntax are used in this benchmark.