const firstObject = {
attempts: 1,
created_at: 1694778031091,
expires_at: 1694778091091,
source: {
externalId: "831f76fc-5a9d-49bc-8d4b-114010cedb73",
name: "Tengen Uzui",
type: "phone",
},
type: "phone",
value: "411273",
};
const finalObject = {
firstObject,
attempts: firstObject.attempts + 1,
};
const firstObject = {
attempts: 1,
created_at: 1694778031091,
expires_at: 1694778091091,
source: {
externalId: "831f76fc-5a9d-49bc-8d4b-114010cedb73",
name: "Tengen Uzui",
type: "phone",
},
type: "phone",
value: "411273",
};
const finalObject = Object.assign({}, firstObject, {
attempts: firstObject.attempts + 1,
});
--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 | 54833268.0 Ops/sec |
Using Object.assign | 7673523.5 Ops/sec |
Let's break down the benchmark and explain what's being tested.
Benchmark Overview
The benchmark compares the performance of two approaches to modify an object: using the spread operator (...
) and Object.assign()
. The test creates an initial object, modifies it, and measures the execution time.
Options Compared
There are two options compared:
...
): This approach uses the spread operator to create a new object by copying the properties of the original object.Object.assign()
: This approach uses the Object.assign()
method to copy the properties of the original object into a new object.Pros and Cons
...
):Object.assign()
:Library and Purpose
In both test cases, no libraries are used explicitly. However, it's worth noting that modern JavaScript environments (e.g., browsers) often include various built-in functions like Object.assign()
.
Special JS Features or Syntax
There is no special JavaScript feature or syntax being tested in this benchmark. Both approaches use standard JavaScript features.
Other Considerations
When choosing between these two approaches, consider the following:
Object.assign()
might be a safer choice.Alternatives
Other alternatives for modifying objects include:
Object.assign()
method with an empty object ({}
) as the destination object: const finalObject = Object.assign({}, firstObject, { attempts: firstObject.attempts + 1 });
cloneDeep()
function to create a deep copy of the original object.Keep in mind that these alternatives may have their own pros and cons, depending on the specific use case.