window.object1 = {};
window.object2 = {};
window.object3 = {};
window.object4 = {};
window.object5 = {};
window.object6 = {};
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 5; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
};
function populate(object) {
for (let i = 0; i < 100; i++) {
object[makeid()] = makeid();
}
};
populate(object1);
populate(object2);
populate(object3);
populate(object4);
populate(object5);
populate(object6);
const object7 = Object.assign({}, object1, object2);
const object7 = {object1, object2};
const object7 = Object.assign(object1, object2);
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Object.assign two objects | |
Spread two objects | |
Object.assign two objects with no empty object first |
Test name | Executions per second |
---|---|
Object.assign two objects | 15845.9 Ops/sec |
Spread two objects | 19808.3 Ops/sec |
Object.assign two objects with no empty object first | 54681.6 Ops/sec |
The benchmark presented compares different methods for merging properties from two JavaScript objects. It specifically evaluates the performance of three approaches: using Object.assign()
, employing the spread operator (...
), and using Object.assign()
with a pre-existing target object.
Object.assign() with a new empty object:
const object7 = Object.assign({}, object1, object2);
object1
and object2
, without mutating either. It's straightforward and widely used.Spread Operator:
const object7 = {...object1, ...object2};
Object.assign()
.Object.assign() with the target object:
const object7 = Object.assign(object1, object2);
object1
by adding properties from object2
. This can be more efficient in terms of memory usage when you do not need to retain the original object.object1
, which may not be desirable in all situations, particularly in functional programming paradigms where immutability is preferred.Memory Overhead: Object.assign({}, obj1, obj2)
creates an additional object, which could lead to increased memory usage, while mutations would result in possible side effects if the original object is expected to remain unchanged.
Readability: The spread operator often enhances readability, especially for developers familiar with modern JavaScript syntax. The simpler syntax can lead to fewer errors during the coding process compared to more verbose alternatives.
lodash.merge
allow for merging objects deeply rather than just shallow merging properties; this is useful for nested objects.Overall, developers should consider their specific use case, including the need for immutability, performance, and clarity of code when choosing between these methods. Each approach has strengths and weaknesses that can influence code performance and maintainability.