var numbers = Array(1000).fill(null).map((x, i) => i.toString());
numbers.reduce((acc, n) => Reflect.set(acc, n, n) && acc, {});
numbers.reduce((acc, n) => Object.assign(acc, { [n]: n }), {});
numbers.reduce((acc, n) => { acc[n] = n; return acc }, {});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Reflect.set | |
Object.assign | |
Direct assignment |
Test name | Executions per second |
---|---|
Reflect.set | 13172.8 Ops/sec |
Object.assign | 885.1 Ops/sec |
Direct assignment | 125975.9 Ops/sec |
Let's break down the provided JSON data for MeasureThat.net, which measures JavaScript microbenchmarks.
Benchmark Definition
The benchmark tests three different approaches to assign values to an object:
numbers.reduce((acc, n) => { acc[n] = n; return acc }, {})
numbers.reduce((acc, n) => Reflect.set(acc, n, n) && acc, {})
numbers.reduce((acc, n) => Object.assign(acc, { [n]: n }), {})
Options Compared
The three approaches differ in how they assign values to the object:
acc[n] = n
) to set the value of each key.Reflect.set
method to dynamically set properties on the object. This method is similar to direct assignment but provides additional features, such as ability to check if a property exists before setting it.Object.assign
method to merge two objects. In this case, it's used to assign individual values to each key in the source array.Pros and Cons
Here are some pros and cons of each approach:
Library/Feature Usage
None of the benchmark cases explicitly uses any libraries or special JavaScript features. However, Reflect.set
is a built-in method in JavaScript's Reflect API.
Other Considerations
When choosing between these approaches, consider the specific requirements of your application:
Alternative Approaches
Other alternatives for object assignment in JavaScript include:
forEach
or map
with the spread operator ({...obj}
) to create a new objectassignIn
method to handle nested objectsKeep in mind that these alternatives may have different performance characteristics and use cases compared to the approaches tested in this benchmark.