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) {
if (obj.hasOwnProperty(key)) {
console.log(obj[key].id);
}
}
}
for (var i=10000; i > 0; i--) {
Object.values(obj).forEach(n => console.log(n.id));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.values |
Test name | Executions per second |
---|---|
for-in | 3.0 Ops/sec |
Object.values | 2.1 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The provided benchmark compares two approaches for iterating over an object in JavaScript:
for-in
loopObject.values()
to get an array of values from the objectFor-In Loop
The for-in
loop is a legacy way of iterating over an object's properties in JavaScript. It iterates over the object's own enumerable properties, not its own methods or symbols. The loop uses the property name as the iteration variable.
Pros:
Cons:
Object.values()
Object.values()
is a modern method introduced in ECMAScript 2017 (ES7) that returns an array containing all values of an object. This approach avoids the issues associated with for-in
loops and provides a more predictable and efficient way to iterate over an object's properties.
Pros:
Library: undefined
There is no library used in this benchmark. The Object.values()
method is a built-in part of the JavaScript language.
Special JS Feature/Syntax: None
This benchmark does not use any special JavaScript features or syntax, such as async/await, generators, or modules.
Other Alternatives
If you need to iterate over an object's properties in JavaScript, other alternatives to for-in
loops and Object.values()
include:
forEach
loop with the in
operator: for (var key in obj) { obj[key].forEach(n => console.log(n.id)); }
Object.keys()
and map()
: Object.keys(obj).map(key => console.log(obj[key].id))
for...of
loops: for (const key of Object.keys(obj)) { console.log(obj[key].id); }
These alternatives provide different trade-offs in terms of performance, readability, and compatibility.