var obj = {};
for (var i = 10000; i > 0; i--) {
obj[`key ${i}`] = i;
}
for (var key in obj) {
console.log(obj[key]);
}
Object.keys(obj).forEach(key => console.log(obj[key]));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 40.5 Ops/sec |
Object.keys | 41.3 Ops/sec |
Benchmark Explanation
MeasureThat.net is testing the performance of two different approaches for iterating over an object in JavaScript: for-in
and Object.keys()
. The benchmark definition provides a simple object with 10,000 properties, each initialized with a unique value.
Approaches Comparison
for
loop with an array-like index (key
). It prints the value of each property to the console.Object.keys()
method to get an array of the object's property names, which is then iterated over using the forEach
method, printing the corresponding property values.Pros and Cons
Library and Special JS Features
Neither benchmark definition uses any external libraries or special JavaScript features. However, it's worth noting that Object.keys()
is a relatively modern feature introduced in ECMAScript 2015 (ES6).
Test Case Explanation
The individual test cases are:
for
loop with an array-like index (key
). It prints the value of each property to the console.Object.keys()
method to get an array of the object's property names, which is then iterated over using the forEach
method, printing the corresponding property values.Other Alternatives
Alternative approaches could include:
for...of
loops or iterators to simplify object iteration.Symbol.iterator
method.However, these alternatives may not be directly comparable to the for-in
and Object.keys()
approaches, as they would require additional setup and potentially alter the benchmark's results.