<script src="https://cdn.jsdelivr.net/lodash/4.16.0/lodash.min.js"></script>
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));
_.forEach(_.values(obj), 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 | |
_.forEach(_.values()) |
Test name | Executions per second |
---|---|
For In | 36.9 Ops/sec |
Object values | 37.6 Ops/sec |
Object keys forEach | 41.8 Ops/sec |
Object entries forEach | 33.8 Ops/sec |
object values forEach | 42.4 Ops/sec |
_.forEach(_.values()) | 36.4 Ops/sec |
Let's break down the benchmark and its various test cases.
Benchmark Overview
The benchmark is designed to compare the performance of different ways to iterate over an object in JavaScript. The goal is to determine which approach is fastest, most efficient, and most readable.
Script Preparation Code
The script preparation code creates a large object with 10,000 properties, each assigned a unique value from 1 to 10,000. This object will be used as the test data for all the benchmark test cases.
Html Preparation Code
The html preparation code includes a reference to the Lodash library, which is used in some of the benchmark test cases. Specifically, the _
variable is an alias for the Lodash object, and _.values()
is used in two of the test cases.
Test Cases
There are six test cases:
for...in
loop.Object.values()
.Object.keys()
and then iterates over each key-value pair using forEach()
.Object.entries()
and then iterates over each pair using forEach()
.forEach()
to iterate over the values._.values()
. This test case is likely included to demonstrate the performance of using a third-party library.Library and Special JS Features
_.values()
and _
.Pros and Cons of Each Approach
Object.values()
is a modern way to access an object's values. Cons: Requires support for modern JavaScript features (ES6+).forEach()
to iterate over the keys. Cons: May be slower than Object.values()
.Object.entries()
is a modern way to access an object's key-value pairs. Cons: Requires support for modern JavaScript features (ES6+).Other Alternatives
for...in
and manual iteration over the object's propertiesArray.prototype.forEach()
or Array.prototype.map()
to iterate over the object's valuesObject.keys()
, Object.values()
, or Object.entries()
in combination with forEach()
or map()