function getObj(i) {
return {
'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
},
[i.toString()]: 1,
};
};
const r = [];
for (var i=10000; i > 0; i--) {
for (var key in getObj(i)) {
r[i] = key;
}
}
console.log(r.length)
const r = [];
for (var i=10000; i > 0; i--) {
Object.keys(getObj(i)).forEach(key => { r[i] = key; });
}
console.log(r.length)
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 252.4 Ops/sec |
Object.keys | 318.1 Ops/sec |
This benchmark compares the performance of different methods for iterating over the properties of an object in JavaScript: the for...in
loop versus the Object.keys
method.
for-in Loop
const r = [];
for (var i = 10000; i > 0; i--) {
for (var key in getObj(i)) {
r[i] = key;
}
}
console.log(r.length);
Object.keys Method
const r = [];
for (var i = 10000; i > 0; i--) {
Object.keys(getObj(i)).forEach(key => {
r[i] = key;
});
}
console.log(r.length);
Pros:
Cons:
Object.keys
in most environments, as demonstrated by the benchmark results where for-in
executed 252.42 operations per second.Pros:
Cons:
forEach
, though this is often negligible in practice.Object.values / Object.entries: Additional methods like Object.values()
and Object.entries()
can be used to retrieve property values or key-value pairs respectively. These methods provide flexibility depending on whether you need keys, values, or both during iteration.
Iterating Performance: In scenarios where performance is critical (e.g., dealing with a large number of object properties or in performance-sensitive applications), using Object.keys
is generally advisable based on this benchmark's results.
Code Readability: Modern JS development highly values readability. Using Object.keys
is often preferred by developers for its clarity about the intent to only iterate over own properties. The functional style of forEach
can also be more expressive compared to traditional loops.
In addition to the methods tested, other alternatives for iterating over object properties include:
Map
or Set
: If you are using collections, these data structures provide methods to iterate over elements with built-in methods.In summary, this benchmark highlights the performance differences between two common object-property iteration techniques in JavaScript. It suggests that while both methods are valid, Object.keys
is generally the more performant and cleaner option for most scenarios.