<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
var person = {name: 'Frederick', lastName: 'Corcino Alejo'};
let age = {age:15};
let copied = _.assign({}, person, age);
let age = {age: 15};
let copied = {person, age};
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash | |
native |
Test name | Executions per second |
---|---|
lodash | 2997968.2 Ops/sec |
native | 3812321.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks on MeasureThat.net.
Benchmark Definition
The benchmark tests two approaches to assign values to an object:
lodash.assign()
...
)Script Preparation Code
The script preparation code defines a variable person
with a nested object:
var person = {name: 'Frederick', lastName: 'Corcino Alejo'};
This setup is used as the source data for both benchmark definitions.
Html Preparation Code
An external library, lodash.js
, is loaded via an HTML script tag to make the lodash.assign()
function available:
<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
Individual Test Cases
There are two test cases:
_.assign()
to create a copied object from person
and the new age
object:let age = {age: 15};
let copied = _.assign({}, person, age);
...
) to create a copied object from person
and the new age
object:let age = {age: 15};
let copied = {...person, ...age};
Pros and Cons of Each Approach
.assign()
):lodash.js
).Library: Lodash
Lodash is a popular utility library for JavaScript that provides a wide range of functions for tasks like array manipulation, object cloning, and more. In this benchmark, lodash.assign()
is used to create a copied object from the input data.
Special JS Feature/Syntax: Spread Operator
The spread operator (...
) is a modern JavaScript feature introduced in ECMAScript 2015 (ES6). It allows you to expand an array or object into a new sequence of elements, creating a shallow copy of the original. In this benchmark, the spread operator is used to create a copied object from person
and the new age
object.
Alternatives
Other alternatives for object assignment might include:
Object.assign()
method (built-in JavaScript function)Keep in mind that these alternatives may have their own trade-offs and performance characteristics, depending on the specific use case and requirements.