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--) {
Object.keys(obj).forEach(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.keys | |
Object.values |
Test name | Executions per second |
---|---|
for-in | 2.8 Ops/sec |
Object.keys | 2.7 Ops/sec |
Object.values | 2.8 Ops/sec |
What is being tested: The provided benchmark tests the performance of three different approaches to iterate over objects in JavaScript:
for-in
loopObject.keys()
methodObject.values()
methodThese approaches are used to print the id
property of each object in the input JSON object.
Options compared:
for-in
: uses a traditional for loop with an explicit iteration variable (var i = 10000;
) and checks each property of the object using in
.Object.keys()
: uses the Object.keys()
method to get an array of property names of the object, which is then iterated over using forEach()
.Object.values()
: uses the Object.values()
method to get an array of property values of the object, which is then iterated over using forEach()
.Pros and Cons:
for-in
loop:Object.keys()
: for...of
loop or forEach()
method, which can add overhead.Object.values()
: Library usage:
None of the benchmark cases use any external libraries. The Object.keys()
and Object.values()
methods are built-in JavaScript features.
Special JS feature or syntax:
No special JavaScript features or syntax are used in these benchmark cases. However, it's worth noting that the for...of
loop (not explicitly used here) is a relatively new feature introduced in ECMAScript 2015, and its usage may affect performance.
Other alternatives: Other alternatives to iterate over objects could include:
Array.prototype.forEach()
with an array of property names or values.Keep in mind that these alternatives may have different performance characteristics and may not be supported in all browsers or environments.