<script src='https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.5/lodash.min.js'></script>
const a = {b:{q: "QWe", w:"ert",e:"ert",r:"ret",t:"rty",y:"werw",u:"ytu",i:"reh",o:"eeh",p:"Weas"}};
_.set(a,".b.c", "what");
const a = {b:{q: "QWe", w:"ert",e:"ert",r:"ret",t:"rty",y:"werw",u:"ytu",i:"reh",o:"eeh",p:"Weas"}};
a.b = { a.b, c: "what" };
const a = {b:{q: "QWe", w:"ert",e:"ert",r:"ret",t:"rty",y:"werw",u:"ytu",i:"reh",o:"eeh",p:"Weas"}};
if(a.b){
a.b.c = "what";
}else{
a.b = {c: "what"};
}
--enable-precise-memory-info
flag.
Test case name | Result |
---|---|
lodash set | |
spread | |
just if |
Test name | Executions per second |
---|---|
lodash set | 357879.9 Ops/sec |
spread | 186686.1 Ops/sec |
just if | 95600944.0 Ops/sec |
Let's dive into the world of JavaScript microbenchmarks!
Benchmark Overview
The benchmark compares three ways to merge or update an object in JavaScript: using Lodash's set
method, spreading the new object using the syntax { ...a.b, c: 'what' }
, and using an if-else statement.
Lodash's set
Method
Lodash is a popular utility library for JavaScript that provides various helper functions. In this case, we're using its set
function to update the value of c
in the object a.b
.
Pros:
Cons:
set
is not a valid method (e.g., older browsers)Spreading Object Literals
The spreading syntax { ...a.b, c: 'what' }
creates a new object with the same properties as a.b
, but with an additional property c
. This approach is often used in modern JavaScript code.
Pros:
Cons:
If-Else Statement
The if-else statement checks if a.b
exists, and if so, updates its value. This approach is often used in older JavaScript code or when working with legacy browsers.
Pros:
Cons:
set
Considerations
When choosing an approach, consider the following factors:
set
method and spreading object literals are often more readable than the if-else statement.Other Alternatives
If you're looking for alternative approaches or optimizations, consider the following:
Object.assign()
instead of spreading syntaxobj-proxy
for more advanced object updatesKeep in mind that benchmarking and optimization can be complex topics. Be sure to thoroughly test your code and consider various factors when choosing an approach.
In conclusion, each approach has its pros and cons, and the choice ultimately depends on your specific use case, performance requirements, and personal preference.