var obj = {
'a': 1,
'b': 2,
'c': 3,
'd': 4,
'e': 5,
'f': 6,
'g': 7
};
for (let i = 0; i < 10000; ++i) {
for (const key in obj) {
console.log(key);
}
}
for (let i = 0; i < 10000; ++i) {
for (const 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.4 Ops/sec |
Object.keys | 0.9 Ops/sec |
Overview of the Benchmark
The provided JSON represents a JavaScript benchmark that compares two approaches to iterate over an object's properties: for-in
loop and using the Object.keys()
method.
What is being tested?
In this benchmark, the following options are compared:
for-in
loop: This is an older way of iterating over an object's properties in JavaScript. It uses a manual index (key
) to access each property.Object.keys()
method: This is a built-in JavaScript method that returns an array of an object's own enumerable property names.Pros and Cons
for-in
loop:
Object.keys()
method:
for-in
loop. Does not include inherited properties in the result.Library
None, as this benchmark uses only built-in JavaScript methods and does not rely on any external libraries.
Special JS Features/Syntax
Object.keys()
method was introduced in ECMAScript 2015 (ES6). This means that older browsers may not support it. To make this benchmark compatible with older browsers, you would need to add a polyfill or use a different approach.Benchmark Preparation Code
The provided preparation code creates an object obj
with 7 properties and assigns them integer values from 1 to 7.
Individual Test Cases
Two test cases are defined:
for-in
loop: This test case uses a traditional for-in
loop to iterate over the object's properties.Object.keys()
method: This test case uses the Object.keys()
method to retrieve an array of property names, which is then iterated using a for...of
loop.Latest Benchmark Result
The benchmark was run on a Chrome browser with version 89.0.4389.82 on a Linux-based desktop device. The results are:
for-in
loop: Executed approximately 1.38 executions per second.Object.keys()
method: Executed approximately 0.90 executions per second.Note that the performance difference between these two approaches is relatively small, but Object.keys()
may be slightly faster due to its optimized implementation.
Alternatives
Other alternatives for iterating over an object's properties include:
for...of
loop with the spread operator (...
) or Array.from()
.for...in
loop with the hasOwnProperty()
method to exclude inherited properties.