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) {
let x = key in obj;
}
}
for (let i=10000; i > 0; i--) {
let keys = Object.keys(obj);
for (let key of keys) {
let x = key in obj;
}
}
for (let i=10000; i > 0; i--) {
let keys = Object.keys(obj);
for (let key of keys) {
let x = keys.includes(key);
}
}
for (let i=10000; i > 0; i--) {
let keys = Object.keys(obj);
for (let key of keys) {
let x = Object.hasOwnProperty(obj, key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
for-of Object.keys | |
for-of Object.keys includes | |
for-of Object.keys hasOwnProperty |
Test name | Executions per second |
---|---|
for-in | 143.1 Ops/sec |
for-of Object.keys | 114.3 Ops/sec |
for-of Object.keys includes | 412.4 Ops/sec |
for-of Object.keys hasOwnProperty | 32.4 Ops/sec |
Let's break down the benchmark and its options.
Benchmark Overview
The benchmark measures the performance of three different approaches to iterate over an object's keys:
for-in
loopObject.keys()
method with for...of
loopincludes()
method with for...of
loophasOwnProperty()
method with for...of
loopOptions Compared
The benchmark compares the performance of these four approaches:
for-in
loop: This is an older way of iterating over object properties using a loop.Object.keys()
method with for...of
loop: This approach uses the Object.keys()
method to get an array of keys, and then iterates over it using a for...of
loop.includes()
method with for...of
loop: This approach uses the includes()
method to check if a key is present in the object, and then iterates over the object's keys using a for...of
loop.hasOwnProperty()
method with for...of
loop: This approach uses the hasOwnProperty()
method to check if a property belongs to the object, and then iterates over the object's properties using a for...of
loop.Pros and Cons of Each Approach
for-in
loop:Object.keys()
method with for...of
loop:Object.keys()
method, which may not be supported in older browsers or environments.includes()
method with for...of
loop:includes()
method.hasOwnProperty()
method with for...of
loop:hasOwnProperty()
method, which may not be supported in older browsers or environments.Library Used
None of these approaches rely on a specific library. However, if we look at the Object.keys()
method and its variants (e.g., includes()
), they are built-in methods provided by modern JavaScript implementations.
Special JS Features/Syntax
This benchmark does not use any special or experimental JavaScript features, such as async/await, generators, or ES6+ modules.
Other Alternatives
If you're looking for alternative ways to iterate over object properties, you might consider:
for...in
loop with the Object.getOwnPropertyNames()
method.for
loop.Keep in mind that each approach has its own trade-offs, and the best choice depends on your specific use case and requirements.