var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1
};
for (let i=10000; i > 0; i--) {
for (let key in obj) {
console.log(obj[key]);
}
}
for (let i=10000; i > 0; i--) {
const keys = Object.keys(obj);
for (let i = 0, iMax = keys.length, key; i < iMax; ++i) {
console.log(obj[keys[i]])
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 1.7 Ops/sec |
Object.keys | 1.6 Ops/sec |
Let's dive into the explanation of what is tested in this benchmark.
Benchmark Definition
The benchmark is comparing two approaches to iterate over an object's keys: for-in
loop and Object.keys()
method.
Options being compared
There are two options being compared:
for-in
loop to iterate over the object's properties.Object.keys()
method to get an array of the object's property names, and then iterates over that array using a traditional for
loop.Pros and Cons
Library
There is no specific library being used in this benchmark. However, the Object.keys()
method is a built-in method in JavaScript that returns an array of the object's property names.
Special JS feature or syntax
There are two special aspects to note:
for...in
loop: This type of loop iterates over the properties of an object using its own property name as the loop variable. It is a proprietary method, not part of the standard JavaScript specification.const keys = Object.keys(obj);
: This syntax uses destructuring assignment to extract the keys
array from the result of calling Object.keys()
. The Object.keys()
method returns an array of strings representing the property names in the object.Other alternatives
If you're interested in exploring alternative approaches, here are a few:
forEach()
: You can use the forEach()
method on arrays to iterate over their elements. For example: obj.keys().forEach(key => console.log(obj[key]));
for
loop with an index variable: You can use a traditional for
loop with an index variable, like this: for (let i = 0; i < obj.length; i++) { const key = obj[i]; console.log(key); }
Keep in mind that these alternatives may have slightly different performance characteristics compared to the two options being compared in this benchmark.