var obj =[new Array(10000)].reduce((o,_,i)=>{
o[i+'-id']={id:i};
return o;
},{});
for (var key in obj) {
console.log(obj[key].id);
}
Object.keys(obj).forEach(key => console.log(obj[key].id));
Object.values(obj).forEach(n => console.log(n.id));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys | |
Object.values |
Test name | Executions per second |
---|---|
for-in | 31.1 Ops/sec |
Object.keys | 34.3 Ops/sec |
Object.values | 34.2 Ops/sec |
Benchmark Overview
The provided benchmark, "for-in vs object.keys vs object.values for objects perf 5", compares the performance of three different approaches to iterate over an array of objects in JavaScript:
for-in
Object.keys()
Object.values()
(introduced in ECMAScript 2019)Options Compared
The benchmark tests the execution speed of each approach on a large dataset of 10,000 objects.
for-in
: uses a traditional for loop to iterate over the object's propertiesObject.keys()
: returns an array of property names that can be iterated over using a foreach loop or other iteration methodsObject.values()
: returns an array of property values that can also be iterated overPros and Cons
Here are some pros and cons of each approach:
Pros:
Cons:
Pros:
for-in
because it avoids iterating over unnecessary propertiesCons:
Pros:
Object.keys()
because it avoids iterating over unnecessary arraysCons:
Library Usage
None.
Special JS Features or Syntax
None mentioned.
Alternative Approaches
Other approaches to iterate over objects in JavaScript include:
Array.prototype.forEach()
with a callback functionfor...of
loops (introduced in ECMAScript 2015)_.forEachObject()
or underscore.js's _each()
However, the benchmark is primarily focused on comparing the performance of Object.keys()
and Object.values()
with traditional for loops (for-in
) and foreach loops (Array.prototype.forEach()
), making these alternatives less relevant to this specific comparison.