Bundle size also matters in javascript performance, and destructuring variable has some caveats in some situations especially when they are function parameters.
First example WITHOUT object destructuring
function add(number1, number2){
return number1 + number2;
}
const result = add(1,5);
// Result
function add(d,n){return d+n}const result=add(1,5);
Input: 86 bytes;Output: 51 bytes;Compression: 40.7%,saving: 35 bytes;
Second example WITH object destructuring
function add({number1, number2}){
return number1 + number2;
}
const result = add({number1: 1, number2: 5});
// Result
function add({number1:n,number2:r}){return n+r}
const result=add({number1:1,number2:5});
Input: 109 bytes;Output: 87 bytes;Compression: 20.18%,saving: 22 bytes;
Third example, using object but no destructuring
function add(opts){
const number1 = opts.number1;
const number2 = opts.number2;
return number1 + number2;
}
add({number1: 1, number2:5});
// Result
function add(n){return n.number1+n.number2}add({number1:1,number2:5});
Input: 148 bytes;Output: 70 bytes;Compression: 52.7%,saving: 78 bytes;
Conclusion
In all situations, object destructuring is the worst bundle size because it can't optimize the names of the objects (maybe there is an option that I forgot). My personal opinion would be to focus on maintainability and therefore readability. I have the feeling that these micro improvements are not worth it if you make your code worse.
BONUS: variable instantiation (out of scope)
In some situations, object destructuring is better from the bundle size point of view. When you initialize variables.
No object destructuring
const obj = {username:"name",lastname:"lastname",age:20};
console.log('break minify optimization');
const username = obj.username;
const lastname = obj.lastname;
const age = obj.age;
// Result
const obj={username:"name",lastname:"lastname",age:20};console.log("break minify optimization");const username=obj.username,lastname=obj.lastname,age=obj.age;
Input: 182 bytes;
Output: 158 bytes;
Compression: 13.19%,
saving: 24 bytes;
With object destructuring
const obj = {username:"name",lastname:"lastname",age:20};
console.log('break minify optimization');
const {username, lastname, age} = obj;
// Result
const obj={username:"name",lastname:"lastname",age:20};console.log("break minify optimization");const{username,lastname,age}=obj;
Input: 138 bytes;
Output: 129 bytes;
Compression: 6.52%,
saving: 9 bytes;
Thanks
Without the answers from nikk wong and Matt I wouldn't have been gone that far in my explanations, up vote their answers too :)
Any feedback is welcome.
js perf {feature}most of the time to get the answer... see jsperf.com/destructuring/5