var obj = {a: 'a', b: 'b'};
const newObj = { obj, c: 'c'};
const newObj = Object.assign(obj, { c: 'c' });
const newObj = Object.assign({}, obj, { c: 'c' });
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Spread | |
Object.assign (mutate) | |
Object.assign (new object) |
Test name | Executions per second |
---|---|
Spread | 2588041.8 Ops/sec |
Object.assign (mutate) | 5209417.5 Ops/sec |
Object.assign (new object) | 1071711.9 Ops/sec |
I'd be happy to explain the benchmark and its results.
Benchmark Overview
The provided JSON represents a JavaScript microbenchmark, which is a small program designed to measure the performance of specific code snippets. In this case, we have three test cases that compare different ways of creating an object with additional properties.
Test Cases
...
) to create a new object with merged properties.const newObj = { ...obj, c: 'c' };
Object.assign()
to mutate an existing object and add new properties.const newObj = Object.assign(obj, { c: 'c' });
Object.assign()
with an initial empty object ({}
) and then merging it with the original object.const newObj = Object.assign({}, obj, { c: 'c' });
Options Compared
The benchmark compares three different approaches to create an object with additional properties:
...
) to merge properties from two objects.Object.assign()
to mutate an existing object and add new properties.Object.assign()
with an initial empty object ({}
) and then merging it with the original object.Pros and Cons
Here's a brief summary of each approach:
Object.assign()
with an existing object.Library and Special JS Feature
None of these test cases use any libraries or special JavaScript features. They only rely on built-in language constructs.
Other Alternatives
If you're looking for alternative ways to create objects with additional properties, some other approaches include:
const newObj = Object.create(obj);
newObj.c = 'c';
push()
and then merge it with another object using Object.assign()
.const arr = [];
arr.push('a');
arr.push('b');
newObj = Object.assign({}, obj, arr);
Note that these alternatives may have different performance characteristics or trade-offs depending on your specific use case.
I hope this explanation helps you understand the benchmark and its results!