var obj = new Object()
var keys = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
for (var key in obj) {
console.log(obj[key]);
}
for(let value of Object.values(obj)){
console.log(value);
}
Object.keys(obj).forEach(key => console.log(obj[key]));
Object.entries(obj).forEach(([key, value]) => console.log(key,'->',value));
Object.values(obj).forEach(value => console.log(value));
const length = Object.keys(obj).lenght
for (var i = 0; i < length ; i++) {
console.log(Object.values(obj)[i])
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys forEach | |
Object entries forEach | |
object values forEach | |
cached length for loop |
Test name | Executions per second |
---|---|
For In | 21.5 Ops/sec |
Object values | 22.4 Ops/sec |
Object keys forEach | 23.3 Ops/sec |
Object entries forEach | 18.3 Ops/sec |
object values forEach | 23.8 Ops/sec |
cached length for loop | 879.0 Ops/sec |
Let's break down the provided benchmark and explain what's being tested, compared, and discussed.
Benchmark Overview
The benchmark measures the performance of different approaches for iterating over an object in JavaScript. Specifically, it compares the following methods:
for...in
loopObject.values()
methodObject.keys()
method with a forEach
loopObject.entries()
method with a forEach
loopApproaches Compared
The benchmark compares the performance of each approach in terms of executions per second (ExecutionsPerSecond). The approach with the highest value is considered faster.
Here's a brief explanation of each approach:
in
operator to check if a property exists.method**: This method returns an array of values in the object, allowing for iteration using standard array methods like
forEach`.method with forEach**: Similar to
Object.values()`, but iterates over the keys instead of values.Pros and Cons
Here are some pros and cons for each approach:
Object.values()
, works well with objects that don't have inherited properties.Object.keys()
), slightly slower than Object.values()
due to method overhead.Library Usage
None of the provided methods rely on external libraries.
Special JavaScript Features/Syntax
There are no special features or syntax used in this benchmark. The focus is solely on comparing different iteration methods for objects.
Other Alternatives
If you're looking for alternative ways to iterate over an object, consider:
_.forEachObject()
.reduce()
method or other functional programming techniques to process the object's values.Keep in mind that this benchmark is focused on comparing different iteration methods, and the best choice ultimately depends on your specific use case and performance requirements.