const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = {
firstObject,
secondObject
};
const firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign({}, firstObject, secondObject);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign |
Test name | Executions per second |
---|---|
Using the spread operator | 3553059.0 Ops/sec |
Using Object.assign | 8254889.0 Ops/sec |
Let's break down what's being tested in this benchmark.
What is being compared?
The benchmark compares two approaches for merging objects in JavaScript:
...
): This syntax was introduced in ECMAScript 2018 (ES2018). It allows you to extract properties from an object and spread them into a new object.Options compared
The benchmark tests the performance difference between using the spread operator (...
) and Object.assign()
to merge two objects: firstObject
and secondObject
.
Pros and Cons of each approach
...
):Object.assign()
due to the overhead of parsing the spread operator.Other considerations
When choosing between these two approaches, consider the following:
...
).Object.assign()
.Library and special JavaScript features
In this benchmark, there are no specific libraries used. However, it's worth noting that the spread operator (...
) was introduced in ECMAScript 2018 (ES2018), so older browsers or environments may not support it.
Benchmark preparation code
The script preparation code is empty, which means the benchmark starts with a clean slate and doesn't include any external dependencies or initialization code.
Other alternatives
If you're interested in exploring alternative approaches, consider the following:
Object.assign()
, but with more flexibility.{}
as the target object for Object.assign()
can provide better performance than using null
or undefined, which may cause browsers to optimize away the assignment.Keep in mind that these alternatives may have different trade-offs and use cases compared to the spread operator (...
) and Object.assign()
.