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--) {
const array = []
for (var key in obj) {
array.push({newid: obj[key].id});
}
}
for (var i=10000; i > 0; i--) {
const array = []
Object.keys(obj).forEach(key => array.push({newid: obj[key].id}));
}
for (var i=10000; i > 0; i--) {
const array = []
Object.values(obj).forEach(n => array.push({newid: n.id}));
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys | |
Object.values |
Test name | Executions per second |
---|---|
for-in | 634.9 Ops/sec |
Object.keys | 553.1 Ops/sec |
Object.values | 408.3 Ops/sec |
Benchmark Overview
The provided benchmark is designed to compare the performance of three different approaches for iterating over objects in JavaScript: for-in
, Object.keys()
, and Object.values()
.
Options Compared
for-in
: This approach uses the in
operator to iterate over the object's properties. It returns an array-like object containing all property names with their corresponding values.Object.keys()
: This approach uses a method of the Object
prototype to return an array of a given object's own enumerable property names as strings.Object.values()
: This approach uses a method of the Object
prototype to return an array containing the values of all properties with enumerable string keys or symbols.Pros and Cons
for-in
:Object.keys()
: Object
prototype, making it easy to access and call.Object.values()
: Symbol
objects.Library Usage
None of the benchmark cases use external libraries, but Object.keys()
and Object.values()
do rely on methods that are part of the Object
prototype.
Special JavaScript Features or Syntax
There are no special features or syntax used in this benchmark. However, it's worth noting that for-in
can also iterate over non-enumerable properties if the object has a __proto__
property (e.g., inherited properties).
Other Alternatives
If you wanted to compare other approaches for iterating over objects, some alternatives could include:
forEach()
loop with a custom callback functionkeyBy
or valuesIn
.each()
However, these approaches are not included in the provided benchmark.