var obj = new Object()
var keys = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
const arr = [];
for (const key in obj) {
arr.push(obj[key]);
}
const arr = Object.values(obj);
const arr = [];
for (const key of Object.keys(obj)) {
arr.push(obj[key]);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys for of |
Test name | Executions per second |
---|---|
For In | 2418.2 Ops/sec |
Object values | 12333.5 Ops/sec |
Object keys for of | 1434.5 Ops/sec |
Let's break down the provided benchmark and its test cases.
Benchmark Overview
The benchmark is designed to compare three approaches for iterating over an object: for-in
, Object.values()
, and Object.keys()
with the for...of
loop. The goal is to determine which approach provides the best performance in JavaScript.
Options Compared
in
operator to iterate over the object's own enumerable properties. It can also include inherited properties, which may impact performance.with
for...ofloop**: This method uses the
Object.keys()function to get an array of the object's own enumerable property names, and then iterates over this array using a
for...of` loop.Pros and Cons of Each Approach
with
for...of` loop:Object.values()
, but allows for more control over property iteration.Object.keys()
.Library and Special JS Features
None are mentioned in the provided benchmark.
Other Considerations
When choosing an approach, consider the following factors:
for-in
might be a better choice.Object.values()
is generally faster due to its optimized implementation.for...of
loop can make code more concise and readable.Alternatives
Other approaches for iterating over objects include:
Array.prototype.forEach()
: This method is similar to for-in
, but uses an array-based iteration instead of a property-based approach.Object.getOwnPropertyNames()
: This method returns an array of all properties (including inherited) on the object, and can be used with forEach()
or other iteration methods.In summary, the benchmark provides a comprehensive comparison of three approaches for iterating over objects in JavaScript, highlighting their pros and cons, and providing guidance on choosing the best approach based on specific requirements.