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--) {
for (var key of Object.keys(obj)) {
console.log(key);
}
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 1.1 Ops/sec |
Object.keys | 1.0 Ops/sec |
I'll break down the provided benchmark for you.
Overview
The test case measures the performance difference between using traditional for-in
loop and using the Object.keys()
method to iterate over an object's properties in JavaScript.
What is being tested?
for-in
loop: This is a traditional way of iterating over an object's properties. It uses a loop variable (key
) that changes on each iteration, allowing access to both the property name and its value.Object.keys()
method: This is a more modern approach to iterating over an object's properties. It returns an array of strings representing the property names, which can be used in a traditional loop.Options being compared
The benchmark compares two approaches:
for-in
loop: This uses a loop variable (key
) that changes on each iteration.Object.keys()
method: This returns an array of strings representing the property names, which can be used in a traditional loop.Pros and Cons
in
flag.Library/Language features
None explicitly mentioned in the benchmark definition.
Special JS feature/syntax
The for...of
loop (not used in this benchmark) and const
(used in some test cases) are notable JavaScript features. However, they are not relevant to this specific benchmark.
Other alternatives
If you want to explore alternative approaches:
Array.prototype.forEach()
: This is a more modern approach to iterating over arrays or objects.for...of
loop: This is a more concise way of iterating over arrays or objects, but not used in this benchmark.while
loop with array indices: This can be a good alternative for arrays, but may not be suitable for objects.Benchmark preparation code
The script prepares an object (obj
) with 11 properties, all initialized to the value 1
. The script then defines two test cases:
for-in
: Uses a traditional for-in
loop to iterate over the object's properties and logs each property name.Object.keys
: Uses the Object.keys()
method to get an array of property names, which is then iterated using a traditional for...loop
.Latest benchmark result
The latest results show that:
for-in
loop performs slightly better than the Object.keys()
method (approximately 9% faster) on this specific test case.