var fruits = {
"orange-id": {
name: "Orange",
taste: "sweet"
},
"apple-id": {
name: "Apple",
taste: "sour"
}
};
var fruitIds = ["orange-id", "apple-id"];
Object.values(fruits);
fruitIds.map(id => fruits[id]);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.values | |
Mapping ids to object |
Test name | Executions per second |
---|---|
Object.values | 6772920.0 Ops/sec |
Mapping ids to object | 7799824.5 Ops/sec |
Let's break down the provided benchmark definition and test cases to understand what is being tested.
Benchmark Definition
The benchmark definition consists of two scripts:
var fruits = {...};
: This script creates an object called fruits
with some properties, including orange-id
and apple-id
, each containing additional properties like name
and taste
.Object.values()
method: This method returns an array containing all the values of a given object.fruitIds.map(id => fruits[id])
expression: This is using the map()
function to create a new array where each element is obtained by looking up the corresponding value in the fruits
object.What are being compared?
The benchmark is comparing two approaches:
Object.values()
method to get an array of values directly from the fruits
object.fruitIds
array to look up each ID in the fruits
object and retrieve its corresponding value.Pros and Cons of each approach:
fruitIds
:Other considerations:
fruits
object), which might not accurately represent real-world performance differences. Larger datasets would likely reveal more pronounced differences between the two approaches.map()
function is used with a simple callback, which might not be representative of more complex scenarios where the callback is more involved.Library usage
There is no explicit library being used in this benchmark definition. However, modern JavaScript environments like Chrome often use internal optimizations and implementations that may affect performance differences between these two approaches.
Special JS feature or syntax
There are no special features or syntaxes being tested here (e.g., async/await, Promises, let
/const
declarations).
Alternatives
Other approaches to achieve the same result could be:
_.map()
), which provides an efficient and readable way to map over arrays.Keep in mind that these alternatives would likely introduce additional overhead, so the performance difference between Object.values()
and mapping over fruitIds
might still be noticeable.