const obj = { foo: 1, bar: 2 };
const finalObject = { baz: 3, obj };
const obj = { foo: 1, bar: 2 };
const finalObject = Object.assign({baz: 3}, obj);
const obj = { foo: 1, bar: 2 };
Object.assign({}, obj, { baz: 3 });
const obj = { foo: 1, bar: 2 };
const obj2 = { baz: 3 };
const finalObject = {obj2, obj };
const obj = { foo: 1, bar: 2 };
const obj2 = { baz: 3 };
const finalObject = Object.assign(obj2, obj );
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Basic object spread | |
Basic assign operator | |
Assign with empty object | |
Spread operator with two existing objects | |
Object assign with two existing objects |
Test name | Executions per second |
---|---|
Basic object spread | 640396.2 Ops/sec |
Basic assign operator | 232981.8 Ops/sec |
Assign with empty object | 208497.2 Ops/sec |
Spread operator with two existing objects | 44896.6 Ops/sec |
Object assign with two existing objects | 260082.2 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks.
Benchmark Purpose:
The MeasureThat.net
benchmark tests how JavaScript engines handle object spread and assignment operations in various scenarios. Specifically, it compares different approaches to create a new object by spreading or assigning existing objects.
Options Compared:
{ ...obj }
, where obj
is an existing object being spread into a new object.Object.assign({ baz: 3 }, obj)
, where obj
is an existing object being assigned to a new object with an initial value of { baz: 3 }
.Object.assign({}, obj, { baz: 3 })
, where obj
is an existing object and an empty object {}
is used as the target for assignment.{ ...obj2, ...obj }
, where both obj2
and obj
are existing objects being spread into a new object.Object.assign(obj2, obj)
, where both obj2
and obj
are existing objects being assigned to a new object.Pros and Cons:
Libraries Used:
In this benchmark, Object.assign()
is used as a library function to facilitate object assignment. It's a standard method for assigning properties from one or more source objects to a target object.
Special JS Features/Syntax: This benchmark doesn't explicitly use any special JavaScript features or syntax beyond the standard syntax for creating new objects using spread and assign operators.
Other Considerations:
Alternatives: To measure object spread and assignment performance, you could use alternative approaches such as:
JSON.parse(JSON.stringify(obj))
for basic spreadingKeep in mind that each approach has its own trade-offs and potential drawbacks. The choice of method depends on the specific requirements and constraints of your project.
If you have any further questions or would like more information on JavaScript performance optimization, feel free to ask!