var a = { a: 'oh', b: 'my' };
var b = { c: 'goddess' };
const c = Object.assign(Object.assign({}, a), b)
const c = {a, b}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign() | |
Spread operator |
Test name | Executions per second |
---|---|
Object.assign() | 1569993.2 Ops/sec |
Spread operator | 1161807.1 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being tested?
The benchmark compares the performance of two approaches to create a new object: Object.assign()
and the spread operator (...
).
Options compared:
Object.assign()
: This method creates a shallow copy of an existing object by assigning properties from one object to another....
): This syntax creates a new object by copying all own enumerable properties from source objects.Pros and cons of each approach:
Object.assign()
:...
):Library and special syntax used:
There is no specific library being tested in this benchmark. However, the spread operator relies on a modern JavaScript feature called "rest parameter syntax" (...
), which was introduced in ECMAScript 2015 (ES6).
Other considerations:
a
with two properties and another object b
with one property to create a new object.{}
to create a new empty object, which allows the comparison to be fair.Alternatives:
If you're interested in creating a new object, there are other methods available:
Object.create()
: Creates a new object with the specified prototype.Array.prototype.slice()
: Can be used to create an array copy, which can then be converted to an object using Object.assign()
.JSON.parse()
: Can be used to parse a JSON string and create a new object.However, these alternatives might not provide the same level of performance or conciseness as the spread operator for simple use cases.