<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 immutable merge | |
immutable object.assign | |
spread |
Test name | Executions per second |
---|---|
lodash immutable merge | 9240230.0 Ops/sec |
immutable object.assign | 37047700.0 Ops/sec |
spread | 49931128.0 Ops/sec |
Overview of the Benchmark
The provided benchmark, hosted on MeasureThat.net, compares the performance of three approaches for merging two objects: lodash
's immutable merge (_.merge()
), object.assign()
(including an immutable version), and the spread operator ({ ...a, ...b }
). The goal is to determine which approach is the fastest.
Options Compared
_.
function from the Lodash library to perform an immutable merge.object.assign()
with a function that returns a new object, ensuring immutability.{ ...a, ...b }
) to create a new object by spreading the properties of two objects.Pros and Cons of Each Approach
Library Used: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functions for tasks such as array manipulation, object manipulation, and more. The _.merge()
function is specifically designed to merge two or more objects into one, ensuring immutability by default.
Special JS Feature/Syntax: None
There are no special JavaScript features or syntaxes used in this benchmark beyond the standard language features supported by all browsers.
Other Considerations
When choosing an approach for merging objects, consider the following factors:
Alternatives
If you're interested in exploring other options, consider:
Object.assign()
without the wrapper function to achieve immutability.Keep in mind that each alternative may have its own trade-offs and considerations, so be sure to evaluate them based on your specific needs and requirements.