var obj = {
'a': 1,
'b': 1,
'c': 1,
'd': 1,
'e': 1,
'f': 1,
'g': 1
};
const arr = [];
for (var i=10000; i > 0; i--) {
for (var key in obj) {
arr.push(key);
}
}
for (var i=10000; i > 0; i--) {
Object.keys(obj).map(key => key);
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
for-in | |
Object.keys |
Test name | Executions per second |
---|---|
for-in | 2369.2 Ops/sec |
Object.keys | 951.4 Ops/sec |
Let's break down what's being tested in this benchmark.
Benchmark Goal: The goal of this benchmark is to compare the performance of three different approaches for iterating over an object and extracting its keys:
for...in
loopObject.keys()
methodmap()
function with Object.keys()
Options Compared:
for...in
loop, which iterates over the object's properties (including inherited ones) and assigns them to a variable in each iteration.map()
function to apply a transformation to each key in the object, which returns an array of keys.Pros and Cons:
map()
function.Library Used (if any): None in this case. The benchmark is testing only JavaScript core features and standard libraries.
Special JS Feature or Syntax: There's no specific special feature or syntax being tested here, just standard JavaScript core features.
Now, let's talk about the benchmark preparation code:
obj
with 11 properties (keys) and assigns a value of 1 to each property.Other Alternatives: Some other alternatives for iterating over objects and extracting keys include:
for...of
loop (which iterates over the object's own properties)forEach()
function with an arrow functionKeep in mind that these alternatives may have different performance characteristics and use cases than the options being tested here.