<script src="https://cdn.jsdelivr.net/npm/lodash@4.17.5/lodash.min.js"></script>
var person = { name: 'Foo', lastName: 'Bar' };
_.set(person, 'age', 10)
person.age = 10
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
Lodash.set | |
Dot notation property setter |
Test name | Executions per second |
---|---|
Lodash.set | 7256724.5 Ops/sec |
Dot notation property setter | 603135744.0 Ops/sec |
I'll break down the explanation into smaller sections to make it easier to understand.
Benchmark Definition and Script Preparation Code
The benchmark definition is a JSON object that describes two test cases:
_.set
function from the Lodash library to set a property on an object.The script preparation code is:
var person = { name: 'Foo', lastName: 'Bar' };
This creates an object named person
with two properties: name
and lastName
.
Library: Lodash
Lodash is a popular JavaScript utility library that provides a lot of useful functions for tasks such as array manipulation, string manipulation, and object manipulation. The _.set
function is part of the Lodash library and allows you to set the value of a property on an object.
Test Cases
The test cases are identical except for how they set the age
property on the person
object:
person.age = 10
_.set(person, 'age', 10)
Both approaches achieve the same result, but they use different syntax.
Comparison
The two test cases are compared to determine which approach is faster.
Pros and Cons
Here's a brief summary of the pros and cons of each approach:
age
property on the object.Other Considerations
When choosing between these two approaches, consider the following:
Other Alternatives
There are other ways to set properties on objects in JavaScript, such as using bracket notation (person['age'] = 10
) or using Object.assign(). However, these approaches are less common and may have slightly different performance characteristics compared to the dot notation and Lodash.set approaches.