<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.js"></script>
var person = {name: 'Frederick', lastName: 'Corcino Alejo'};
_.assign({}, person);
Object.assign({}, person);
a = {person}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash Assing | |
Native Assing | |
spread |
Test name | Executions per second |
---|---|
Lodash Assing | 3015881.0 Ops/sec |
Native Assing | 4937886.5 Ops/sec |
spread | 5084315.5 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark, hosted on MeasureThat.net, measures the performance of three approaches for assigning properties to an object: Lodash's _assign
, the native Object.assign()
method, and the spread operator (...
).
Test Cases
The benchmark consists of three test cases:
_assign
function to assign properties to an empty object._.assign({}, person);
Object.assign()
method to assign properties to an empty object.Object.assign({}, person);
...
) to assign properties to an empty object.a = {...person};
Library: Lodash
Lodash is a popular JavaScript utility library that provides a wide range of functional programming helpers. In this benchmark, Lodash's _assign
function is used to concatenate two or more objects into one.
Spread Operator (...
)
The spread operator is a syntax sugar introduced in ECMAScript 2015 (ES6) for creating new arrays from iterable sources. When used with objects, the spread operator creates a new object by spreading the properties of an existing object into a new object.
Native Object.assign()
Method
The native Object.assign()
method was introduced in ECMAScript 2015 (ES6) and is used to assign own enumerable properties of source objects to target objects. This method is implemented in most modern JavaScript engines.
Options Compared
In this benchmark, the following options are compared:
_assign
function.Object.assign()
method....
).Object.assign()
.Other Considerations
When choosing an approach, consider the following factors:
Object.assign()
method or spread operator may be a better choice._assign
function might be more convenient.Alternatives
Other alternatives for assigning properties to objects include:
push()
can be used to assign properties to an array. However, this approach is less efficient and more prone to errors.Object.assign()
and the spread operator: (a = {...b}).assign(c);