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--) {
const keys = Object.keys(obj)
for (let key of keys) {
console.log(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 1.2 Ops/sec |
Object.keys | 0.9 Ops/sec |
Benchmark Explanation
The provided JSON represents a JavaScript microbenchmark test case on the MeasureThat.net website. The benchmark compares the performance of two approaches to iterate over an object's properties:
for
loop with the in
keyword to iterate over the object's properties.Object.keys()
method to get an array of the object's property names, which is then iterated over using a for...of
loop.Options Comparison
The two approaches have different pros and cons:
Object.keys()
method to be supported by the browser or engine being tested.Other Considerations
i
in the traditional for
loop and key
in the for...of
loop). The choice of loop variable does not affect the performance of the benchmark.in
keyword lookup may become more significant.Library and Special JS Features
None of the provided benchmarks use a library or special JavaScript features that would affect the interpretation of the results.
Alternative Approaches
If you want to explore alternative approaches for iterating over an object's properties, consider the following:
Object.keys()
or for-in
are not suitable.Benchmark Preparation Code
The provided script preparation code creates an object with 11 properties and assigns the value 1
to each property:
var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1,
'h': 1,
'i': 1,
'j': 1,
'k': 1
};
The HTML preparation code is empty, indicating that no specific HTML or CSS setup is required for this benchmark.