<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var a = { a: 'oh', b: 'my' };
var b = { c: 'goddess' };
var c = _.merge(a, b);
var a = { a: 'oh', b: 'my' };
var b = { c: 'goddess' };
var c = _.assign(a, b);
var a = { a: 'oh', b: 'my' };
var b = { c: 'goddess' };
var c = Object.merge(a, b);
var a = { a: 'oh', b: 'my' };
var b = { c: 'goddess' };
var c = { a, b };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
_.merge | |
_.assign | |
Object.assign | |
Spread |
Test name | Executions per second |
---|---|
_.merge | 2863408.8 Ops/sec |
_.assign | 3723854.2 Ops/sec |
Object.assign | 0.0 Ops/sec |
Spread | 22364566.0 Ops/sec |
I'll explain the benchmark and its various aspects.
Benchmark Overview
The MeasureThat.net website provides a microbenchmarking tool to compare the performance of different JavaScript functions for merging objects. The benchmark compares four methods: _.merge
, _.assign
, Object.assign
, and the spread operator ({ ...a, ...b }
).
Test Cases
Each test case consists of two variables a
and b
, with a
containing properties a
and b
, and b
containing property c
. The goal is to merge these two objects into a new object.
_.merge
, but returns the destination object, allowing for chaining multiple assignments.Library and Purpose
_.merge
and _.assign
. These functions are used for merging objects.JavaScript Features
{ ...a, ...b }
): Introduced in ECMAScript 2018 (ES10), this feature allows creating a new object by merging the properties of two or more existing objects._.assign(a, b)
vs Object.assign(b, a)
): The _ (Lodash)_
functions use a chaining approach for multiple assignments, whereas the built-in Object.assign
function does not support chaining.Pros and Cons
null
properties).Benchmarking Considerations
Alternatives
merge-deep
or lodash.merge
.