<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var a = { a: 'oh', b: 'my' };
var c = _.merge({a:true}, a);
var a = { a: 'oh', b: 'my' };
var c = Object.assign({a:true}, a);
var a = { a: 'oh', b: 'my' };
var c = { a:true, a };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash merge | |
object.assign | |
spread |
Test name | Executions per second |
---|---|
lodash merge | 6155501.0 Ops/sec |
object.assign | 12627836.0 Ops/sec |
spread | 40911312.0 Ops/sec |
Let's break down the provided benchmark and explain what is being tested.
Benchmark Overview
The benchmark measures the performance of three different approaches to merge objects in JavaScript: _.merge
from Lodash, Object.assign
, and spread operator (...
). The test creates two objects, a
and b
, with some common properties. Then, it defines a new object c
using each of these methods.
Options Compared
The benchmark compares the performance of three approaches:
Object.assign
: This method copies all enumerable own properties from one or more source objects to a target object....
) with overwrite: This method uses the spread operator to create a new object and then assigns the a
object to it, overwriting any common properties.Pros and Cons
Object.assign
:**...
with overwrite):**Library
The benchmark uses the Lodash library, which provides a merge
function to merge two objects into one. This library is widely used and well-regarded in the JavaScript community.
Special JS Feature/Syntax
...
) with overwrite syntax, which was introduced in ECMAScript 2018 (ES2018) as part of the Object Spread Operator (Spread Syntax) feature. This syntax allows you to create a new object and then assign an existing object to it using the spread operator.Other Alternatives
If you're interested in exploring other alternatives for merging objects, here are some options:
Object.assign()
with nested objects: You can use Object.assign()
recursively by calling it on each property of the source object.merge-deep
or lodash.merge Deep
: These libraries provide more advanced merge functionality that handles nested objects and other edge cases.for...in
loop: You can write a custom implementation using a for...in
loop to iterate over the properties of both objects and assign values to the new object.