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,
};
for (let i=10000; i > 0; i--) {
for (const key in obj) {
console.log(key);
}
}
for (let i=10000; i > 0; i--) {
Object.keys(obj).forEach(key => console.log(key));
}
for (let i=10000; i > 0; i--) {
for (const key of Object.keys(obj)) {
console.log(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys | |
for..of Object.keys |
Test name | Executions per second |
---|---|
for-in | 2.8 Ops/sec |
Object.keys | 2.3 Ops/sec |
for..of Object.keys | 2.6 Ops/sec |
The provided benchmark measures the performance of three different ways to iterate over the keys of an object in JavaScript: using for-in
, for..of
with Object.keys()
, and using Object.keys()
directly.
Options being compared:
Object.keys()
: This method uses a newer syntax to iterate over the keys of an object and uses the Object.keys()
function to get an array of those keys.Object.keys()
function without any iteration mechanism.Pros and Cons:
Library and Special JS Feature:
None mentioned in the provided benchmark.
Other Considerations:
When choosing between these options, consider the following factors:
for-in
may be a safer choice.For..of
with Object.keys()
is likely to be the fastest option due to its optimized iteration mechanism.for...of
with Object.keys()
, as it provides a clear and concise way to iterate over object keys.Alternatives:
Other alternatives for iterating over object keys include:
in
operator (e.g., for (key in obj) { ... }
)forEach()
method on an array of keys (e.g., Object.keys(obj).forEach(key => { ... })
)Keep in mind that these alternatives may have different performance characteristics or trade-offs with respect to readability and maintainability.