function createArray(propsCount) {
const arr = []
for (let i = 0; i < propsCount; i += 1) {
arr.push({
id: i,
value: i + ' value'
})
}
return arr
}
var data = createArray(100)
const obj = Object.fromEntries(data.map(item => [item.id, item.value]));
const obj = Object.assign({}, data.map((item) => ({[item.id]: item.value})));
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.fromEntries | |
Object.assign |
Test name | Executions per second |
---|---|
Object.fromEntries | 87117.6 Ops/sec |
Object.assign | 11404.5 Ops/sec |
Let's break down the benchmark and its components.
Benchmark Definition
The benchmark is designed to compare two ways of converting an array of objects into an object using JavaScript's Object.fromEntries
and Object.assign
. The conversion involves mapping each object in the array, transforming it into a key-value pair, and then creating an object from these pairs. This process is repeated 100 times (due to the use of the createArray(100)
function) for performance comparison.
Options Compared
Two approaches are compared:
...
).Pros and Cons of Each Approach
Object.assign
. It's also more expressive and readable.Object.fromEntries
. May require additional steps for more complex conversions.Library Used
None explicitly mentioned in the benchmark definition; however, both methods rely on built-in JavaScript functionality.
Special JS Feature/Syntax (None)
No special features or syntax are used beyond standard JavaScript.
Other Considerations
The benchmark is designed to measure performance differences between Object.fromEntries
and Object.assign
, which are widely used methods in modern web development. This comparison can help developers decide which approach to use based on their specific needs, browser support requirements, and personal preference.
Alternatives
For this particular conversion task, other approaches could include:
_.mapValues
) or Ramda (R.mapKeys
), which provide more concise and expressive ways to perform similar conversions.Map
objects (e.g., creating an object from key-value pairs using map.entries()
).However, these alternatives are not specifically tested in this benchmark.