const obj1 = { a: "a" };
const obj2 = { b: "b" };
function _defineProperty(obj, key, value) {
if (key in obj) {
Object.defineProperty(obj, key, {
value: value,
enumerable: true,
configurable: true,
writable: true
});
} else {
obj[key] = value;
}
return obj;
}
function ownKeys(object, enumerableOnly) {
var keys = Object.keys(object);
if (Object.getOwnPropertySymbols) {
var symbols = Object.getOwnPropertySymbols(object);
if (enumerableOnly) symbols = symbols.filter(function (sym) {
return Object.getOwnPropertyDescriptor(object, sym).enumerable;
});
keys.push.apply(keys, symbols);
}
return keys;
}
function _objectSpread2(target) {
for (var i = 1; i < arguments.length; i++) {
var source = arguments[i] != null ? arguments[i] : {};
if (i % 2) {
ownKeys(Object(source), true).forEach(function (key) {
_defineProperty(target, key, source[key]);
});
} else if (Object.getOwnPropertyDescriptors) {
Object.defineProperties(target, Object.getOwnPropertyDescriptors(source));
} else {
ownKeys(Object(source)).forEach(function (key) {
Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key));
});
}
}
return target;
}
window.obj1 = obj1;
window.obj2 = obj2;
window._objectSpread2 = _objectSpread2;
const finalObject = {
a: "a",
obj2
};
const finalObject = Object.assign({ a: "a" }, obj2);
_objectSpread2({ a: "a" }, obj2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Using the spread operator | |
Using Object.assign | |
Babel |
Test name | Executions per second |
---|---|
Using the spread operator | 6454847.5 Ops/sec |
Using Object.assign | 3509055.2 Ops/sec |
Babel | 881407.1 Ops/sec |
Let's break down the benchmark and explain what is being tested.
Benchmark Definition
The benchmark definition provides three different ways to merge two objects: obj1
and obj2
. The goal is to compare the performance of these three approaches.
const finalObject = {...obj2}
): This approach uses the spread operator (...
) to create a new object that includes all properties from obj1
and obj2
.Object.assign()
method to merge two objects.Options Compared
The three options are compared in terms of their performance, measured by the number of executions per second (ExecutionsPerSecond
).
Pros and Cons of Each Approach
lodash
for deep merges).Library Usage
None of the options use any external libraries beyond what is included in the benchmark definition (e.g., Object
).
Special JS Feature or Syntax
There are no special JS features or syntaxes being tested in this benchmark. The focus is on comparing three different approaches to merge objects.
Alternatives
Other alternatives for merging objects include:
merge()
function: A popular utility library that provides a robust and efficient way to merge objects._extend()
function: Another popular utility library that provides a simple and concise way to merge objects.It's worth noting that the benchmark results show Chrome 103 outperforming other browsers and environments in terms of performance.