function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
window.parentObj = {};
for (let i = 0; i < 100; i++) {
window.parentObj[makeid()] = makeid();
}
Object.entries(window.parentObj).map(([id, name]) => {
return {id, name}
});
Object.keys(window.parentObj).map(id => {
const name = window.parentObj[id];
return { id, name };
});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.entries | |
Object.keys |
Test name | Executions per second |
---|---|
Object.entries | 128656.1 Ops/sec |
Object.keys | 51759.2 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares two approaches to iterate over an object in JavaScript: Object.entries
and Object.keys
. The test case creates an object with 100 keys (unique identifiers) and values, generated randomly using a custom function makeid()
. The goal is to determine which approach is faster for this specific use case.
Options Compared
Two options are being compared:
Object.entries()
: This method returns an array of key-value pairs in the object, where each pair is an array with two elements: the key and the value.Object.keys()
: This method returns an array of strings representing the keys of the object.Pros and Cons
Here's a brief overview of each approach:
Object.entries()
:Object.keys()
:Object.entries()
.Library and Purpose
In this benchmark, no libraries are explicitly used. However, window.parentObj
is a custom object created in the script preparation code. Its purpose is to serve as a test subject for iterating over its key-value pairs using both Object.entries()
and Object.keys()
methods.
Special JS Feature or Syntax (None)
There are no special JavaScript features or syntax used in this benchmark.
Alternative Approaches
If you need to iterate over an object's keys, other approaches might include:
for (var key in obj) { ... }
for (const [key, value] of Object.entries(obj)) { ... }
(not used in this benchmark)keys()
function: _object.keys()
Keep in mind that the choice of approach depends on your specific use case and performance requirements.
Benchmark Preparation Code Explanation
The script preparation code creates an object with 100 random keys and values, assigns it to window.parentObj
, and then iterates over its key-value pairs using both Object.entries()
and Object.keys()
methods. The resulting benchmark data is stored in the RawUAString
property of each test case.
Latest Benchmark Result Explanation
The latest benchmark result shows the execution per second for each browser (in this case, only Firefox 102) on a Linux desktop system. The values indicate that Object.entries()
outperforms Object.keys()
, with approximately 2.5 times more executions per second.