var obj = new Object()
var keys = (new Array(10000)).fill(0).map((x, i) => { return i + 1 })
keys.forEach((x) => { obj['prop' + x] = x })
const keys = Object.keys(obj);
for (let j1 = 0; j1 < keys.length; j1++) {
const key = keys[ j1 ];
const value = obj[ key ];
const result = key + value;
}
const entries = Object.entries(obj);
for (let j1 = 0; j1 < entries.length; j1++) {
const entry = entries[ j1 ];
const key = entry[0];
const value = entry[1];
const result = key + value;
}
const keys = Object.keys(obj);
const values = Object.values(obj);
for (let j1 = 0; j1 < keys.length; j1++) {
const key = keys[j1];
const value = values[j1];
const result = key + value;
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object keys | |
Object entries | |
Object values |
Test name | Executions per second |
---|---|
Object keys | 753.1 Ops/sec |
Object entries | 595.1 Ops/sec |
Object values | 449.7 Ops/sec |
Let's break down the provided JSON and explain what's being tested.
Benchmark Definition
The benchmark tests three ways to create objects in JavaScript:
Object.keys()
: creates an array of property names of an objectObject.values()
: creates an array of property values of an objectObject.entries()
: creates an array of tuples containing both the key and value of each propertyOptions being compared
The benchmark compares the performance of these three methods for creating objects, specifically when iterating over the properties to perform some operation (in this case, concatenating a key with a value).
Pros and Cons of each approach:
Object.keys()
:Object.values()
:Object.keys()
, requires an extra step to iterate over the properties to use their values.Object.entries()
:Library usage
None of the benchmark cases explicitly uses any libraries. However, the JavaScript engine being used (V8) is an open-source library developed by Google.
Special JS features or syntax
The benchmark uses const
declarations for variables and arrow functions, which are relatively recent syntax additions to JavaScript (introduced in ECMAScript 2015). They are not essential to understanding the performance comparison, but they are commonly used in modern JavaScript code.
Alternative approaches
Other methods to create objects in JavaScript that might be worth exploring in a benchmark include:
Object.create()
and setting properties manually.for...in
or for...of
loops to iterate over object properties.Keep in mind that each approach has its trade-offs in terms of performance, readability, and maintainability.