var obj = {};
for (let i = 0; i < 100; i++) {
obj[`k_${i}`] = i;
}
for (const [k, v] of Object.entries(obj)) console.log(k, v);
for (const k of Object.keys(obj)) console.log(k, obj[k]);
for (const k in obj) console.log(k, obj[k]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.entries | |
Object.keys | |
for...in |
Test name | Executions per second |
---|---|
Object.entries | 1200.6 Ops/sec |
Object.keys | 1249.5 Ops/sec |
for...in | 1345.5 Ops/sec |
What is being tested?
On the provided JSON, three JavaScript microbenchmarks are defined to compare the performance of different approaches to iterate over an object:
for...in
loopObject.keys()
methodObject.entries()
methodThese methods are used to access and manipulate the properties of an object.
Options compared
The benchmark compares the performance of these three approaches:
for...in
: a traditional loop that iterates over the properties of an object using the in
keyword.Object.keys()
: returns an array of strings containing the property names of an object.Object.entries()
: returns an array of tuples containing the property keys and values of an object.Pros and cons
Here's a brief summary of each approach:
for...in
in some cases.Library and special JS feature
None of these methods rely on external libraries or specific JavaScript features beyond the standard object model.
However, note that for...in
can be affected by the Strict Mode
behavior, which was introduced in ECMAScript 5. In Strict Mode, for...in
only iterates over enumerable properties, whereas in Non-Strict Mode, it also includes non-enumerable properties. The benchmark does not specify whether to use Strict or Non-Strict Mode.
Other alternatives
If you need to iterate over an object's properties and values, other approaches might include:
forEach()
method: obj.forEach(function(value, key) { console.log(key, value); });
for
loop with array indices: for (var i = 0; i < obj.length; i++) { console.log(obj[i]); }
map()
, filter()
, and other array methods to extract the desired values.Keep in mind that these alternatives might not be as efficient or straightforward as using one of the three original approaches, depending on your specific use case.