const secondObject = { moreData: 'foo bar' }
const finalObject = { secondObject };
const secondObject = { moreData: 'foo bar' }
const finalObject = Object.assign({}, 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 | 64464312.0 Ops/sec |
Using Object.assign | 4061211.2 Ops/sec |
What is tested?
MeasureThat.net is testing the performance of two different methods for creating a shallow copy of an object in JavaScript: the spread operator (...
) and Object.assign()
. The benchmark is measuring how fast each method can create a new object with some of the properties from an existing object.
Options compared
There are two options being compared:
...
): This method creates a new object by iterating over the properties of the original object and adding them to the new object using the spread operator.Pros and cons
...
):Object.assign()
in older browsers or environments where support is limited.Other considerations:
Object.assign()
may perform better due to its ability to handle arrays and objects with functions.Object.assign()
with an untrusted source can lead to security vulnerabilities.Libraries and special JS features
In this benchmark, no libraries are used beyond the standard JavaScript features. However, it's worth noting that in other cases, MeasureThat.net may use additional libraries or features, such as async/await for handling asynchronous operations.
No special JavaScript features are used in this specific benchmark.
Other alternatives
If you want to create a shallow copy of an object in JavaScript, there are other methods available:
const finalObject = Object.assign({}, secondObject);
const finalObject = { ...secondObject };
(not exactly the same as the spread operator, but achieves similar results)Keep in mind that each of these alternatives has its own trade-offs and may not be suitable for all use cases. The spread operator (...
) is generally considered the most modern and efficient way to create a shallow copy of an object in JavaScript.