<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 = Object.assign(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 |
---|---|
lodash merge | |
object.assign | |
spread |
Test name | Executions per second |
---|---|
lodash merge | 3533454.0 Ops/sec |
object.assign | 8052452.5 Ops/sec |
spread | 7658243.5 Ops/sec |
I'd be happy to help explain the benchmark.
What is being tested?
MeasureThat.net is testing three different approaches for merging two objects in JavaScript:
_.merge
from Lodash libraryObject.assign
{ ...a, ...b }
)These approaches are being compared to determine which one is the most efficient.
Options comparison
Here's a brief overview of each option and their pros and cons:
_
.merge
from Lodash library
Pros:
Cons:
The _.merge
function takes two objects as input and returns a new merged object. It also supports other data types like arrays.
Object.assign
Pros:
Cons:
Object.assign
is a built-in JavaScript function that takes multiple targets and an array of key-value pairs as arguments. When used with two objects, it returns a new merged object.
{ ...a, ...b }
)Pros:
Cons:
The spread syntax allows you to create a new object by spreading an existing object's properties onto a target object. When used with two objects, it returns a new merged object.
Library and syntax features
Lodash is a popular utility library for JavaScript that provides various functions for tasks like string manipulation, array processing, and more. In this benchmark, _.merge
is used to merge objects.
The spread syntax ({ ...a, ...b }
) is a modern JavaScript feature introduced in ECMAScript 2018 (ES2018). It allows you to create a new object by spreading an existing object's properties onto a target object.
Other alternatives
If these three approaches are not sufficient for your needs, here are some additional options:
Object.create
: can be used to create a new object with the desired properties, but it requires more code and might lead to shallow merges if used incorrectly.Keep in mind that the best approach depends on your specific use case, performance requirements, and the environment where your code will run.