<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var a = { a: 'foo', b: 'bar' };
var b = { c: 'foobar' };
var c = _.merge(a, b);
var a = { a: 'foo', b: 'bar' };
var b = { c: 'foobar' };
var c = Object.assign(a, b);
var a = { a: 'foo', b: 'bar' };
var b = { c: 'foobar' };
var c = { a, b };
var a = { a: 'foo', b: 'bar' };
var b = { c: 'foobar' };
a = { a, b };
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash merge | |
object.assign | |
spread | |
spread mutate |
Test name | Executions per second |
---|---|
Lodash merge | 2502013.0 Ops/sec |
object.assign | 5099818.5 Ops/sec |
spread | 19495836.0 Ops/sec |
spread mutate | 20728946.0 Ops/sec |
Let's dive into the details of what is being tested in this benchmark.
The provided JSON represents a JavaScript microbenchmark that compares four different approaches for merging objects:
_.merge(a, b)
): This method is part of the popular Lodash library and provides a flexible way to merge two or more objects. It recursively merges properties from source (the first object) into target (the second object).Pros:
Cons:
Object.assign()
: This method is a built-in JavaScript function that returns a new object with the properties of one or more source objects.Pros:
Cons:
{ ...a, ...b }
): This syntax was introduced in ECMAScript 2018 (ES2020) and provides a concise way to merge two or more objects.Pros:
Cons:
a = { ...a, ...b }
): This syntax is similar to the previous one but modifies the original object instead of creating a new one.Pros:
Cons:
The benchmark measures the execution time of each approach on a simple object merge scenario. The Html Preparation Code
includes the Lodash library to ensure that all test cases use the same environment.
In terms of special JavaScript features or syntax, this benchmark uses the spread operator (introduced in ECMAScript 2018) and object mutation with spread operator (a = { ...a, ...b }
). These are relatively new features and may not be supported by older browsers or environments.
Other alternatives to these approaches include:
However, for most use cases, the four approaches mentioned above (Lodash merge, Object.assign()
, spread operator, and spread operator mutation) are sufficient and efficient.