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));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
For In | |
Object values | |
Object keys forEach | |
Object entries forEach | |
object values forEach |
Test name | Executions per second |
---|---|
For In | 50.6 Ops/sec |
Object values | 49.0 Ops/sec |
Object keys forEach | 52.2 Ops/sec |
Object entries forEach | 37.8 Ops/sec |
object values forEach | 52.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Overview
The benchmark being tested is a comparison of four different ways to iterate over an object in JavaScript: for
loop, Object.values()
, Object.keys().forEach()
, and Object.entries().forEach()
.
Test Cases
Each test case represents a specific iteration method:
for
loop.Object.values()
method to get an array of the object's property values.Object.keys()
method and the forEach()
method to iterate over the object's property keys.Object.entries()
method and the forEach()
method to iterate over the object's key-value pairs.Library: None
None of the test cases use any external libraries, making them self-contained and easily reproducible.
Special JavaScript Features/Syntax
Pros and Cons of Each Approach
for
loops and potentially more memory usage.for
loops and creates an array of property keys in a single step.Object.values()
or Object.keys().forEach()
, as it requires creating an array of key-value pairs.Other Alternatives
If you need to iterate over an object in JavaScript, other alternatives include:
Array.prototype.forEach()
with a custom callback function.map()
method to create a new array of values.In conclusion, each test case represents a different approach to iterating over an object in JavaScript. While there is no clear winner in terms of performance, Object.values()
and Object.keys().forEach()
tend to be faster and more efficient. The choice of method ultimately depends on the specific requirements and constraints of your use case.