var originalObject = {
a: 1,
b: "string",
c: true,
};
const copyObject = Object.assign({}, originalObject, { c: false });
const copyObject = { originalObject, c: false };
const copyObject = {
a: originalObject.a,
b: originalObject.b,
c: false,
};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object assign | |
Spread operator | |
Manually |
Test name | Executions per second |
---|---|
Object assign | 11070142.0 Ops/sec |
Spread operator | 11066430.0 Ops/sec |
Manually | 947081728.0 Ops/sec |
Let's break down what's being tested in the provided benchmark.
The main goal of this benchmark is to compare three different approaches for creating a new object and then modifying one of its properties.
Approaches compared:
Object.assign()
function to create a new object by copying the existing object (originalObject
) and adding or replacing some properties.{ ... }
) to create a new object by spreading the existing object's properties and then updating one of them.Pros and cons of each approach:
Object.assign()
function, and might not be as efficient if the object has many properties.Object.assign()
due to the overhead of creating a new object, and can be less efficient if the object has many properties.Library usage:
None of the approaches rely on any external libraries.
Special JS feature/syntax:
The benchmark uses the spread operator ({ ... }
) which is a relatively modern JavaScript feature introduced in ECMAScript 2018. It allows creating a new object by spreading the properties of an existing object into it.
Benchmark preparation code and test cases:
The script preparation code creates an originalObject
with three properties: a
, b
, and c
. The benchmark then defines three test cases:
Object.assign()
with the original object as the first argument, and an additional property { c: false }
.{ ... }
) and updates one of its properties.The benchmark then runs these tests on Firefox 106 with multiple executions per second, comparing the performance of each approach.
Alternative approaches:
Other alternatives for creating a new object might include:
Object.create()
to create an object and then updating its properties.cloneDeep()
function to create a deep copy of the original object.However, these alternatives might not be as relevant in this specific benchmark, which is focused on comparing the performance of three simple approaches.