var obj = {
'a': {
id: 'a',
num: 1
},
'b': {
id: 'b',
num: 1
},
'c': {
id: 'c',
num: 1
},
'd': {
id: 'd',
num: 1
},
'e': {
id: 'e',
num: 1
},
'f': {
id: 'f',
num: 1
},
'g': {
id: 'g',
num: 1
},
};
for (var i=10000; i > 0; i--) {
for (var key in obj) {
console.log(obj[key].id);
}
}
for (var i=10000; i > 0; i--) {
const values = Object.values(obj);
for (n of values) {
console.log(n.id)
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.values |
Test name | Executions per second |
---|---|
for-in | 8.8 Ops/sec |
Object.values | 7.7 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares three approaches for iterating over objects in JavaScript:
for-in
object.keys
(or Object.keys
)object.values
(or Object.values
)These approaches are used to iterate over an object's properties and access their values. The benchmark is designed to measure which approach is the fastest.
Options Compared
The options being compared are:
for-in
: This method iterates over an object's own enumerable properties using a loop with a counter variable (i
). It also allows accessing the property name (in this case, key
) and the value.object.keys
/ Object.keys
: This method returns an array-like object containing the names of all own enumerable properties. The benchmark uses for...of
loop to iterate over this array and access the property values.object.values
/ Object.values
: Similar to object.keys
, but returns an array-like object containing the values of all own enumerable properties.Pros and Cons
Here's a brief summary of each approach:
object.keys
/ Object.keys
:object.values
/ Object.values
:object.keys
, but returns an array of values instead of property names.Library and Special JS Features
There are no libraries used in this benchmark. However, it does use the for...of
loop syntax, which is a feature introduced in ECMAScript 2015 (ES6).
Other Alternatives
Besides the three approaches being compared (for-in
, object.keys
, and object.values
), other alternatives for iterating over objects include:
forEach
method on an array of property names or values.reduce
function to iterate over properties and accumulate results.for-in
approach).Keep in mind that each approach has its trade-offs, and the best choice depends on the specific use case and performance requirements.
Benchmark Context
The benchmark is likely used to:
By understanding the trade-offs and characteristics of each approach, developers can make informed decisions when working with objects in JavaScript.