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 = {
c: "a",
obj1,
obj2
};
const finalObject = Object.assign({ c: "a" }, obj1, obj2);
_objectSpread2({ c: "a" }, obj1, 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 | 17217832.0 Ops/sec |
Using Object.assign | 28609574.0 Ops/sec |
Babel | 2821409.0 Ops/sec |
I'll explain the benchmark and its options in detail.
Benchmark Overview
The benchmark measures the performance of three different approaches to merge two objects: Object.assign
, the spread operator (...
), and Babel's _objectSpread2
function.
Approaches Compared
Object.assign()
method to create a new object by merging the properties of two existing objects....
): This approach uses the spread operator (...
) to merge the properties of two objects into a new object._objectSpread2
function: This is a custom implementation of the spread operator, written in JavaScript and compiled by Babel.Pros and Cons of Each Approach
JSON.parse()
and JSON.stringify()
....
):_objectSpread2
function:Other Considerations
obj1
and obj2
) with different properties to simulate real-world usage scenarios.Library Used
The _objectSpread2
function is a custom implementation by Babel. It's not a traditional library in the sense that it's part of the Babel compiler and transpilation process.
Special JS Feature or Syntax
None mentioned explicitly. However, the spread operator (...
) is a relatively recent feature introduced in ECMAScript 2015 (ES6), which might require support for newer browsers or environments.