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
},
};
var arr = [
{
id: 'a',
num: 1
},
{
id: 'b',
num: 1
},
{
id: 'c',
num: 1
},
{
id: 'd',
num: 1
},
{
id: 'e',
num: 1
},
{
id: 'f',
num: 1
},
{
id: 'g',
num: 1
},
];
for (var i=10000; i > 0; i--) {
arr.forEach(i => {
console.log(i.id === 'e')
})
}
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 | 10.6 Ops/sec |
Object.keys | 10.3 Ops/sec |
Object.values | 10.4 Ops/sec |
The benchmark described in the provided JSON compares three different approaches to iterating over JavaScript objects and arrays, specifically focusing on retrieving and checking the id
property of object entries. The primary test cases being compared are:
for...in
loop. Object.keys()
to get keys of the object. Object.values()
to get values of the object.for-in
Loop Benchmark:
for (var i=10000; i > 0; i--) {
arr.forEach(i => {
console.log(i.id === 'e');
});
}
for...in
loop to iterate over the properties of the arr
array, checking if the id
of each item equals 'e'
.hasOwnProperty
checks.Using Object.keys()
:
for (var i=10000; i > 0; i--) {
Object.keys(obj).forEach(key => console.log(obj[key].id));
}
obj
object using Object.keys()
and iterates over them to access the corresponding values.Using Object.values()
:
for (var i=10000; i > 0; i--) {
Object.values(obj).forEach(n => console.log(n.id));
}
obj
using Object.values()
, and this directly iterates over these values.Object.keys()
, it avoids inherited properties.From the benchmark results:
for-in
approach executes approximately 10.59 executions per second, making it the fastest in this comparison.Object.values()
follows with about 10.41 executions per second.Object.keys()
is the slowest, with approximately 10.32 executions per second.When choosing the best method for iterating over object properties:
for-in
may be faster but with potential risks of including prototype properties.Object.keys()
and Object.values()
convey their purpose directly, compared to for-in
.forEach
makes sense, while objects may want specific handling for their own properties.Other alternatives could include:
for...of
: For arrays, this syntax can provide a cleaner way to iterate over arrays directly, focusing on their values.map
, filter
, and reduce
can lead to concise and often more readable code for transformations and selections, though these involve additional overhead.This benchmark is useful for a broad range of software engineers, providing insights into both performance and code clarity when choosing how to iterate over objects in JavaScript.