const firstObject = { sampleData: 'Hello world' }
const finalObject = {
firstObject
};
const firstObject = { sampleData: 'Hello world' }
const finalObject = Object.assign(firstObject);
const firstObject = { sampleData: 'Hello world' }
const finalObject = { sampleData: firstObject.sampleData }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Using mutation |
Test name | Executions per second |
---|---|
Using the spread operator | 141882640.0 Ops/sec |
Using Object.assign | 11884886.0 Ops/sec |
Using mutation | 1021811072.0 Ops/sec |
Let's dive into the benchmark definition and explain what is being tested.
The test case is comparing three approaches to create a new object with similar data:
...
)Object.assign()
Options compared:
...
): This operator allows you to create a new object by copying all the own enumerable properties from an existing object.Object.assign()
: This method copies all enumerable own properties from one or more source objects to a target object.Pros and Cons of each approach:
...
):Object.assign()
Object.assign()
:Object.keys()
or for...in
)Library/Features:
There are no explicit libraries used in this benchmark.
Special JS features or syntax:
The benchmark uses the spread operator (...
), which is a relatively new feature introduced in ECMAScript 2018. It allows you to create a new object by copying all the own enumerable properties from an existing object.
Considerations:
When choosing between these approaches, consider the trade-offs between readability, performance, and memory allocation. If readability is more important than performance, the spread operator might be a better choice. However, if speed is critical, Object.assign()
might be a better option. For cases where nested objects are involved, the spread operator provides a convenient way to handle them without additional configuration.
Alternatives:
Other approaches that could be used for this benchmark include:
const { sampleData } = firstObject; const finalObject = { sampleData };
)JSON.parse()
and JSON.stringify()
cloneDeep
function)However, these alternatives might not be as straightforward or readable as the spread operator, Object.assign()
, or mutation.