const firstObject = { sampleData: 'Hello world' }
const finalObject = {
firstObject,
};
const firstObject = { sampleData: 'Hello world' }
const finalObject = Object.assign({}, firstObject);
--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 | 14595909.0 Ops/sec |
Using Object.assign | 4140411.8 Ops/sec |
Let's break down the benchmark and its test cases.
Benchmark Overview
The benchmark is designed to compare the performance of two approaches: using the spread operator (...
) and Object.assign
to create a new object by copying data from an existing object, specifically a single object with a sample property. The goal is to determine which approach is faster for non-destructive copying of a single object.
Options Compared
Two options are being compared:
...
): This method creates a new object by spreading the properties of the original object into the new object.Object.assign
: This method creates a new object by copying the specified properties from an existing object.Pros and Cons
...
):Object.assign
:Library Used
In this benchmark, none of the test cases use any external libraries. However, it's worth noting that Object.assign
is a built-in JavaScript method, so no additional library is required.
Special JS Features/Syntax
The spread operator (...
) was introduced in ECMAScript 2018 (ES2018) and became part of the standard in ES2020. It's a modern feature that allows for concise object creation and manipulation.
Benchmark Preparation Code
Since there is no Script Preparation Code provided, we'll assume it's not necessary to set up any specific environment or variables before running the benchmark. The focus is solely on comparing the performance of the two approaches.
Alternatives
If you need to compare other methods for creating a new object by copying data from an existing object, some alternatives include:
Object.create()
: Creates a new object with the specified prototype.Array.prototype.slice()
or Array.prototype.concat()
: Can be used to create a shallow copy of an array or object.Keep in mind that these alternatives may have different performance characteristics and trade-offs compared to the spread operator and Object.assign
.