const obj = {hello:"world"};
const newOne = Object.assign({}, obj);
const obj = {hello:"world"};
const newOne = {obj};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign | |
Direct |
Test name | Executions per second |
---|---|
Object.assign | 4028175.8 Ops/sec |
Direct | 31352464.0 Ops/sec |
Let's break down the JavaScript microbenchmark on MeasureThat.net.
Benchmark Definition
The benchmark measures the performance of two approaches to create a shallow copy of an object in JavaScript:
Object.assign()
: This method creates a new object with the specified properties, copied from the original object.{...obj}
: This syntax is called "object spread" or "spread operator." It creates a new object with the same properties as the original object.Options Compared
The benchmark compares these two approaches:
Pro of Object.assign()
: It is a widely supported method in older browsers, and it provides more control over the creation process.
Con of Object.assign()
: It can lead to slower performance due to the overhead of creating a new object and copying properties.
Pros of {...obj}
: It is faster and more concise than using Object.assign()
.
Cons of {...obj}
:
Library Used
None. This benchmark only uses built-in JavaScript features.
Special JS Features/Syntax
Yes, the Object.assign()
method is used, which is a built-in JavaScript function. The {...obj}
syntax is also supported in modern browsers and JavaScript engines.
Benchmark Preparation Code
The script preparation code is empty, as no custom logic or setup is required for this benchmark.
Other Alternatives
Besides the two approaches tested here, other methods to create shallow copies of objects include:
Array.prototype.slice()
with Object.assign()
: Creates a new array and then uses Object.assign()
to copy properties from the original object.lodash
library's cloneDeep()
, assign()
, or pick()
methods: Provides more flexibility and customization options, but comes with a performance overhead due to the library.In summary, this benchmark helps measure the performance difference between using Object.assign()
versus the spread operator syntax for creating shallow copies of objects in JavaScript.