const firstObject = {}
firstObject.sample1 = 'Hello world';
firstObject.sample2 = 'foo bar';
const firstObject = { }
const secondObject = { firstObject, sample1: 'foo bar' }
const finalObject = { secondObject, sample2: 'Hello world' }
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using update | |
Using Object.assign |
Test name | Executions per second |
---|---|
Using update | 119415592.0 Ops/sec |
Using Object.assign | 34574624.0 Ops/sec |
The benchmark titled "JavaScript spread operator vs object update performance 2" evaluates two different methods for updating JavaScript objects to determine which is more efficient.
Using Update:
const firstObject = {};
firstObject.sample1 = 'Hello world';
firstObject.sample2 = 'foo bar';
This test case initializes an empty object (firstObject
) and directly adds properties to it.
Using Object Assign:
const firstObject = {};
const secondObject = { ...firstObject, sample1: 'foo bar' };
const finalObject = { ...secondObject, sample2: 'Hello world' };
In this scenario, the test creates a new object (secondObject
) by using the spread operator (...
) to copy properties from firstObject
and adds a new property (sample1
). It then creates another new object (finalObject
) again using the spread operator to include properties from secondObject
and adds another new property (sample2
).
The benchmark results indicate the following executions per second:
This shows that directly updating an object is significantly faster than creating new objects using the spread operator.
Using Update:
Using Object Assign (via spread operator):
...
) is a feature of ES6 (ECMAScript 2015) that allows for expanding iterable objects into places like function calls or array literals. In the context of objects, it allows for creating shallow copies of objects and merging properties from multiple objects.Object.assign()
can also be used for similar operations, the spread syntax is generally more concise and is preferred for readability in many contemporary JavaScript codebases.Object.assign({}, firstObject, { sample1: 'foo bar' })
for creating new object instances, though it will also typically be slower than direct object updates.In conclusion, the benchmark shows that while using updates is more performant, it sacrifices some immutability benefits. Choosing the right approach often depends on the specific requirements of the application and the desired trade-offs between performance and immutability.