var a = { a: 1, b: 2, c: 3};
return Object.values(a);
var a = { a: 1, b: 2, c: 3};
return Object.keys(a).reduce((prev, key) => {
prev.push(a[key]);
return prev;
},[]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.values | |
Keys, Reduce |
Test name | Executions per second |
---|---|
Object.values | 19476534.0 Ops/sec |
Keys, Reduce | 23447594.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark compares the performance of two approaches to access values in an object:
Object.values
Object.keys
with the reduce()
methodWhat are Object.values and Object.keys?
Object.values
returns an array of a given object's own enumerable property values.
Object.keys
returns an array of a given object's own enumerable property keys (i.e., names).
The reduce()
method applies a function to each element in the array and reduces it to a single value. In this case, we're using it to concatenate the values from the Object.keys(a)
array into a single array.
Options Compared
We have two options being compared:
Object.values
: Directly access the object's values as an array.Object.keys()
and then apply reduce()
to concatenate the key names into an array of values.Pros and Cons of Each Approach
Object.values
:Object.values
.Object.keys()
and reduce()
).Other Considerations
When choosing between these approaches, consider the following:
Object.values
is likely a better choice.Keys, Reduce
might be a better option.Library and Special JS Features
Neither of these approaches relies on any specific library or special JavaScript features beyond what's built into the language.