TIL Optimizations with closures
POSTED ON:
TAGS: javascript closures optimization
To reduce the number of times a variable gets computed, you can use closures. Closures work by storing references to the outer function’s variables. They do not store the actual value.
function findCustomerCity(name) {
const texasCustomers = ['John', 'Ludwig', 'Kate'];
const californiaCustomers = ['Wade', 'Lucie','Kylie'];
return texasCustomers.includes(name) ? 'Texas' :
californiaCustomers.includes(name) ? 'California' : 'Unknown';
};
If we call the above functions several times, each time a new object is created. For every call, memory is unnecessarily re-allocated to the variables texasCustomers
and californiaCustomers
.
With closures, we can instantiate the variables only once.
function findCustomerCity() {
const texasCustomers = ['John', 'Ludwig', 'Kate'];
const californiaCustomers = ['Wade', 'Lucie','Kylie'];
return name => texasCustomers.includes(name) ? 'Texas' :
californiaCustomers.includes(name) ? 'California' : 'Unknown';
}
let cityOfCustomer = findCustomerCity();
cityOfCustomer('John'); //Texas
cityOfCustomer('Wade'); //California
cityOfCustomer('Max'); //Unknown
This was a small change. We move the parameter to the innerfunction
.
This is much more performant, as the objects are already stored in memory thanks to closures.
Via https://www.joyk.com/dig/detail/1594756891396192
Related TILs
Tagged: javascript