var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1,
'h': 1,
'i': 1,
'j': 1,
'k': 1,
'l': 1,
'm': 1,
'n': 1,
'o': 1,
'p': 1,
'q': 1,
'r': 1,
's': 1,
't': 1,
'u': 1,
'v': 1,
'w': 1,
'x': 1,
'y': 1,
'z': 1,
'aa': 1,
'ba': 1,
'ca': 1,
'da': 1,
'ea': 1,
'fa': 1,
'ga': 1,
'ha': 1,
'ia': 1,
'ja': 1,
'ka': 1,
'la': 1,
'ma': 1,
'na': 1,
'oa': 1,
'pa': 1,
'qa': 1,
'ra': 1,
'sa': 1,
'ta': 1,
'ua': 1,
'va': 1,
'wa': 1,
'xa': 1,
'ya': 1,
'za': 1,
'ab': 1,
'bb': 1,
'cb': 1,
'db': 1,
'eb': 1,
'fb': 1,
'gb': 1,
'hb': 1,
'ib': 1,
'jb': 1,
'kb': 1,
'lb': 1,
'mb': 1,
'nb': 1,
'ob': 1,
'pb': 1,
'qb': 1,
'rb': 1,
'sb': 1,
'tb': 1,
'ub': 1,
'vb': 1,
'wb': 1,
'xb': 1,
'yb': 1,
'zb': 1
};
for (var i=10000; i > 0; i--) {
for (var key in obj) {
console.log(key);
}
}
for (var i=10000; i > 0; i--) {
var keys = Object.keys(obj);
for (var j = 0; j < keys.length; j ++) {
console.log(keys[j]);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 0.3 Ops/sec |
Object.keys | 0.3 Ops/sec |
This benchmark compares two ways to iterate over the properties of a large JavaScript object:
1. for...in
loop: This is a traditional way to iterate over an object's enumerable properties. The code snippet for this test uses nested loops – one for decrementing a counter and another using for...in
to iterate through each property name in the object.
2. Object.keys()
: This method returns an array containing all enumerable property names of an object. The code snippet for this test uses a for
loop to iterate through the resulting array.
for...in
, as it avoids unnecessary iterations and provides a consistent order of iteration (alphabetical). Other considerations:
for...in
or Object.keys()
.Alternatives:
Let me know if you have any other questions!