var obj1 = { a: 1, b: 2 };
var obj2 = { b: 2, c: 3 };
const obj3 = { obj1, obj2 };
const obj3 = Object.assign({}, obj1, obj2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Object.assign |
Test name | Executions per second |
---|---|
Spread | 1358886.6 Ops/sec |
Object.assign | 2025186.2 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being tested?
The benchmark is testing two approaches to create a new object by merging two existing objects: the spread operator (...
) and Object.assign()
.
Options compared:
...
):const obj3 = { ...obj1, ...obj2 };
Object.assign()
is a method that returns a new object with the properties from the specified source objects.const obj3 = Object.assign({}, obj1, obj2);
Pros and Cons:
...
):proto
property is preserved (not tested in this benchmark)Library usage:
None, as both approaches are native JavaScript syntax.
Special JS feature/syntax:
...
) uses the rest parameter syntax, which was introduced in ECMAScript 2015 (ES6).Object.assign()
is a standard method defined by the ECMAScript specification.Other considerations:
Both approaches have their own use cases and performance characteristics. In general, the spread operator is preferred for its concise syntax, while Object.assign()
is often used when working with older browsers or environments that don't support the spread operator.
Alternatives:
For creating a new object by merging two existing objects, you can also consider other approaches:
Object.create()
and then adding properties to it using the hasOwnProperty()
method.Keep in mind that these alternatives might have their own trade-offs in terms of performance, readability, and support across browsers and environments.