var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1
};
let res = 0;
for (var i=10000; i > 0; i--) {
for (var key in obj) {
res = obj[key];
}
}
let res = 0;
for (var i=10000; i > 0; i--) {
const keys = Object.keys(obj);
const l = keys.length;
for (var e=0; e < l; e++) {
res = obj[keys[e]];
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 84.1 Ops/sec |
Object.keys | 68.7 Ops/sec |
This benchmark compares two JavaScript approaches to iterating over the properties of an object: using a for...in
loop versus using Object.keys()
to retrieve an array of the object's keys and then iterating over that array with a traditional for
loop.
for-in Loop:
let res = 0;
for (var i = 10000; i > 0; i--) {
for (var key in obj) {
res = obj[key];
}
}
for...in
statement iterates over the enumerable properties of an object. In this benchmark, it accesses each property of obj
, which contains simple key-value pairs.Object.keys() Method:
let res = 0;
for (var i = 10000; i > 0; i--) {
const keys = Object.keys(obj);
const l = keys.length;
for (var e = 0; e < l; e++) {
res = obj[keys[e]];
}
}
Object.keys()
method creates an array of a given object’s own enumerable property names, iterating over that array provides access to the values via the keys.Pros:
Cons:
hasOwnProperty
if there are inherited properties that should be ignored.Pros:
Cons:
According to the benchmark results from a specific setup:
for-in
loop achieved 84.15 executions per second, while the Object.keys()
approach achieved 68.66 executions per second.for-in
loop performed better.When choosing between these two methods, developers should evaluate:
Object.keys()
may be the better choice despite slightly higher overhead.Other alternatives for iterating over object properties include:
Object.entries(obj).forEach()
provides an iterator that returns both keys and values but may have overhead for larger objects.Map
may be more effective, as they maintain insertion order and offer methods for easy iteration.In conclusion, the choice between for...in
and Object.keys
hinges on the specific requirements of your application, including element properties, performance needs, and readability.