const a = {
hello: "world",
world: "hello"
};
const b = {a, right: "wrong", wrong: "right"};
const a = {
hello: "world",
world: "hello"
};
const b = Object.assign({}, a, {right: "wrong", wrong: "right"});
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
object destruct | |
Object.assign |
Test name | Executions per second |
---|---|
object destruct | 1115649.1 Ops/sec |
Object.assign | 4325169.5 Ops/sec |
Let's break down the provided benchmark and explain what's being tested.
The benchmark measures the performance difference between two approaches: object destructuring and Object.assign()
when creating a new object with some common properties from an existing object, while also adding new properties.
Approaches Compared:
{...a, right: "wrong", wrong: "right"}
to create a new object that inherits the properties of a
and adds the specified additional properties.Object.assign()
method to merge two objects together: one is an existing object a
, and another is an object with the added properties { right: "wrong", wrong: "right"}
.Pros and Cons of Each Approach:
Other considerations:
Object.assign()
merges the objects on the deepest level.{...a}
) is a relatively recent feature in JavaScript (introduced in ECMAScript 2018), and some older browsers might not support it.Library Used:
None explicitly mentioned. However, Object.assign()
uses the native JavaScript method to merge objects.
Special JS Feature or Syntax:
{...a}
): This is a relatively new feature in JavaScript (introduced in ECMAScript 2018) that allows creating a new object with spread properties from an existing object. It's used in both benchmark test cases.Now, let's talk about other alternatives:
Other methods to create a new object with some common properties from an existing object include:
Object.create()
: const b = Object.create(a)(right: "wrong", wrong: "right")
Object.prototype property
accessors: for (const key in a) if (!a.hasOwnProperty(key)) { b[key] = value; }
lodash
library's merge()
methodKeep in mind that these alternatives might have different performance characteristics or may require additional setup, so they're not typically considered standard methods for creating new objects.
In summary, the benchmark measures the performance difference between object destructuring and Object.assign()
when creating a new object with some common properties from an existing object.