var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1
};
for (var i=10000; i > 0; i--) {
for (var key in obj) {
console.log(key);
}
}
for (var i=10000; i > 0; i--) {
Object.keys(obj).forEach(key => console.log(key));
}
for (var i=10000; i > 0; i--) {
for (var key of Object.keys(obj)) {
console.log(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys map | |
Object.keys loop |
Test name | Executions per second |
---|---|
for-in | 3.7 Ops/sec |
Object.keys map | 3.4 Ops/sec |
Object.keys loop | 3.5 Ops/sec |
Overview
The provided JSON represents a benchmark test case on the MeasureThat.net website, which compares the performance of three different approaches to iterate over an object's keys: for-in
, Object.keys
with map
, and Object.keys
with a traditional loop.
Tested Approaches
in
operator to check if a property is present in the object, and then iterates over the properties using a for
loop.Object.keys()
method to get an array of the object's keys, and then uses the forEach()
method to iterate over the array, logging each key to the console.Object.keys()
method to get an array of the object's keys, and then uses a traditional for
loop with a variable declaration (var key
) to iterate over the array, logging each key to the console.Pros and Cons
for-in
since it avoids the overhead of property checks. Also, uses modern JavaScript features like map()
.map()
and can be slower for smaller arrays due to the function call overhead.Object.keys map
since it avoids the overhead of property checks. Also, uses a traditional for
loop with a variable declaration, which can be familiar to developers.Library and Syntax
The benchmark test case uses no external libraries or special JavaScript features beyond what is required by each approach. The only notable feature is the use of modern JavaScript methods like map()
in the Object.keys map
approach, which is supported by most modern browsers.
Other Alternatives
If you were to implement this benchmark yourself, you could also consider using other approaches, such as:
keys()
functionfor...of
loops and spread operator (Object.keys(obj)
→ for (const key of Object.keys(obj))
)Keep in mind that these alternatives may not be directly comparable to the MeasureThat.net benchmark, as they would require modifications to the original test case.