var params = { b:"hello", c: true, d:7 };
var newObj = { a: 2 };
var other = Object.assign({},newObj, params);
var params = { b:"hello", c: true, d:7 };
var newObj = { a: 2 };
var other = { newObj, params };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
spread operator |
Test name | Executions per second |
---|---|
Object.assign | 3684784.0 Ops/sec |
spread operator | 9398957.0 Ops/sec |
I'll explain what's tested in the provided JSON, compare options, pros and cons of those approaches, and discuss other considerations.
What is being tested?
The benchmark tests two JavaScript methods: Object.assign
and the spread operator (also known as rest parameter syntax). The test creates an object with some initial properties (newObj
) and another object with additional properties (params
). The objective is to merge these two objects into a new one, which is stored in the other
variable.
Options compared
There are two options being compared:
Object.assign()
: This method takes multiple source objects as arguments and merges them into a target object....
): This syntax allows you to create a new object by spreading the properties of an existing object or array.Pros and Cons
Object.assign()
:
Pros:
Cons:
Spread operator (...
):
Pros:
Object.assign()
.Cons:
Other considerations
Both methods have their trade-offs. Object.assign()
is more reliable and flexible, while the spread operator provides a cleaner syntax. However, the spread operator's performance may vary depending on the browser and JavaScript engine.
In this benchmark, the results suggest that the spread operator has an advantage in terms of execution speed.
Library usage
There are no libraries being used in these test cases.
Special JS features or syntax
The spread operator is a relatively new feature introduced in ECMAScript 2015. It allows using rest parameters (...
) to create new objects from existing ones.
Alternatives
Other alternatives for merging objects could be:
lodash.merge()
: A popular utility library that provides an efficient and flexible way to merge objects.Object.create()
+ Object.assign()
: This approach involves creating a new object using Object.create()
and then assigning properties using Object.assign()
.for
loops or Array.prototype.forEach()
to iterate over the source objects' properties and assign them to the target object.Keep in mind that these alternatives might not be as concise or readable as the spread operator, but they can provide a more traditional approach to merging objects.