let firstObject = { sampleData: 'Hello world' }
const secondObject = { moreData: 'foo bar' }
firstObject = {
firstObject,
secondObject
};
let firstObject = { sampleData: 'Hello world' }
firstObject = Object.assign(firstObject, { moreData: 'foo bar' });
const firstObject = { sampleData: 'Hello world' }
firstObject.moreData = 'foo bar'
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
add |
Test name | Executions per second |
---|---|
Using the spread operator | 17770806.0 Ops/sec |
Using Object.assign | 4747118.0 Ops/sec |
add | 680403520.0 Ops/sec |
Let's dive into the benchmark and explain what's being tested.
Benchmark Overview
The test compares three different approaches to add or merge properties to an object:
...
)Object.assign()
moreData = 'foo bar'
)Test Case 1: Using the Spread Operator
In this test, we create two objects: firstObject
with a single property sampleData
, and secondObject
with another property moreData
. We then use the spread operator (...
) to merge these two objects into one. The goal is to measure the performance of this approach.
Test Case 2: Using Object.assign()
In this test, we create the same two objects as before and use Object.assign()
to merge them together.
Test Case 3: Adding Properties Directly
In this test, we modify the original firstObject
directly by adding a new property moreData
. This approach is likely to be slower than the first two because it involves re-assigning the object's properties.
Library and Purpose
None of these approaches rely on any external libraries. The spread operator (...
) is a built-in JavaScript feature introduced in ES6, while Object.assign()
is also a built-in method.
Special JS Feature or Syntax
The spread operator (...
) is a new way to merge objects that was introduced in ECMAScript 2015 (ES6). It allows you to expand an object into another object using the syntax { ...obj }
. This feature has become widely adopted and is now supported by most modern browsers.
Performance Considerations
The performance of these approaches can vary depending on the specific use case:
...
): This approach is likely to be the fastest because it involves a simple object merge operation, which can be optimized by the browser.Object.assign()
: This approach may be slower than the spread operator because Object.assign()
involves creating a new object and then assigning properties to it. However, modern browsers have optimized Object.assign()
for performance.Other Alternatives
Other approaches to merge objects include:
concat()
method: let result = { ...firstObject }; result.concat(secondObject);
merge()
function from a library like LodashObject.defineProperty()
However, these alternatives are not tested in this benchmark.
Overall, the test provides valuable insights into the performance characteristics of different approaches to merge objects in JavaScript.