var obj = new Object()
var keys = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
var sum = 0
for (var key in obj) {
sum++
}
var sum = 0
Object.keys(obj).forEach(val => { sum++ })
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object keys forEach |
Test name | Executions per second |
---|---|
For In | 848.7 Ops/sec |
Object keys forEach | 879.8 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Definition:
The benchmark is designed to compare two approaches for iterating over an object in JavaScript: for...in
loop and Object.keys()
with forEach()
method.
Script Preparation Code:
The script creates a new object obj
with 10,000 properties (using the fill()
method and then mapping a function to create each property). The script then sets up an empty variable sum
.
Html Preparation Code: There is no HTML preparation code provided for this benchmark.
Individual Test Cases:
var sum = 0;
for (var key in obj) {
sum++;
}
* This approach iterates over the object's properties using a `for...in` loop, which includes inherited properties.
var sum = 0;
Object.keys(obj).forEach(val => {
sum++;
});
* This approach uses the `Object.keys()` method to get an array of the object's own enumerable property names, and then iterates over that array using the `forEach()` method.
Pros and Cons:
for...in
(as it doesn't iterate over inherited properties)for...in
for modern JavaScript engines (due to caching and optimization)Library: There is no library used in this benchmark.
Special JS feature/syntax: None mentioned.
Other Considerations:
for...in
loop iterates over all properties, including inherited ones, which can lead to slower performance for large objects.Object.keys()
with forEach()
may benefit from caching in some cases.Alternatives: Other alternatives for iterating over an object in JavaScript include:
for
loop with indexing (e.g., for (var key = 0; key < obj.length; key++)
)entries()
method to iterate over both keys and values simultaneously (e.g., for (const [key, value] of Object.entries(obj))
)Note that these alternatives may have different performance characteristics compared to the original benchmark.