var firstObject = { sampleData: 'Hello world' }
firstObject.moreData = 'foo bar'
firstObject = {firstObject}
const finalObject = Object.assign({}, firstObject, { moreData: 'foo bar' });
--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 | 3059366.5 Ops/sec |
Using Object.assign | 3482274.0 Ops/sec |
I'd be happy to explain what's being tested in this JavaScript microbenchmark.
Benchmark Overview
The benchmark measures the performance difference between two approaches for assigning new properties to an object:
...
): This method uses the spread operator (...
) to create a shallow copy of the original object and then updates its moreData
property.Object.assign()
: This method creates a new object by copying all enumerable own properties from the source objects (in this case, the original firstObject
).Options Compared
The benchmark compares two options:
...
) to assign new properties to an objectObject.assign()
method to create a new object and then assigning properties to itPros and Cons of Each Approach:
...
):Object.assign()
:Library Usage
There is no external library used in this benchmark. The JavaScript core functionality is being tested.
Special JS Feature or Syntax
The benchmark uses the spread operator (...
), which is a relatively modern feature introduced in ECMAScript 2018 (ES2018). It's not essential to know how to use it, but understanding its basics can be helpful for creating similar code in the future.
Other Considerations
When writing JavaScript performance benchmarks like this one, consider the following:
Alternatives
Other alternatives for assigning new properties to an object include:
Object.prototype.hasOwnProperty.call()
method to check if a property already exists before assigning it.Object.create()
method and then updating its properties.