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 | 1764053.4 Ops/sec |
Using Object.assign | 4891538.5 Ops/sec |
Benchmark Overview
The MeasureThat.net website allows users to create and run JavaScript microbenchmarks, including the provided benchmark: "JavaScript spread operator vs Object.assign performance GifCo". This benchmark compares the performance of two approaches to merge objects in JavaScript.
Options Compared
Two options are compared:
...
operator is used to merge two objects into a new object. Specifically, the test creates two objects, firstObject
and secondObject
, and then uses the spread operator (...
) to merge them into a single object, finalObject
.Object.assign()
method is used to copy properties from one or more sources (in this case, secondObject
) into a target object (firstObject
).Pros and Cons of Each Approach
...
operatorLibrary Used
None.
Special JS Feature or Syntax
The ...
operator used in the spread operator approach is a new JavaScript feature introduced in ECMAScript 2018 (ES10). This allows for concise merging of objects and arrays. If your target environment doesn't support this feature, you may need to use an alternative approach or polyfill.
Benchmark Results
According to the latest benchmark results, Chrome 109 on Windows Desktop achieved:
These results suggest that using Object.assign()
is generally faster than the spread operator approach.
Alternative Approaches
Other ways to merge objects in JavaScript include:
merge
function from a library like Lodash or Underscore.jsKeep in mind that each approach has its pros and cons, and the best choice depends on your specific use case, target environment, and performance requirements.