const obj = { sampleData: 'Hello world' }
const finalObj = {
obj,
single: 'foo'
};
const obj = { sampleData: 'Hello world' }
const finalObj = Object.assign(obj, { single: 'foo' });
--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 | 75536248.0 Ops/sec |
Using Object.assign | 35290612.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
What is being tested?
The provided benchmark compares the performance of two approaches to create a new object by spreading an existing object and adding new properties: using the spread operator (...
) and using Object.assign()
. The test case focuses on creating a single addition operation, which means only one property is added to the original object.
Options compared
Two options are being tested:
{ ...obj, ...single }
to create a new object that inherits properties from obj
and adds the single
property.Object.assign()
: This approach uses the method Object.assign(obj, { single: 'foo' })
to merge two objects: the original object obj
and an object with the single
property.Pros and Cons
Object.assign()
:Library: Object.assign()
Object.assign()
is a built-in JavaScript method that returns a new object with the properties of all the specified source objects. It is used extensively in modern JavaScript development and is supported by most browsers and Node.js versions.
Special JS feature/syntax: None mentioned
This benchmark does not use any special JavaScript features or syntax beyond what's commonly known.
Other alternatives
While Object.assign()
has been widely adopted, there are other methods that can achieve similar results:
const finalObj = { ...obj, ...['single'] }
. Note that this creates an array, which may lead to unexpected behavior if not handled correctly.const finalObj = Object.fromEntries([[...obj, single: 'foo']]
. This approach is more explicit but has similar performance characteristics to Object.assign()
.In summary, the benchmark compares two approaches to create a new object by spreading an existing object and adding a new property. The spread operator offers concise code with good performance, while Object.assign()
provides a well-established method with slightly less efficient overhead.