Today I Learned - Rocky Kev

TIL Optimizations with closures

POSTED ON:

TAGS:

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:

TIL what is npm Script

Despite their high usage they are not particularly well optimized and add about 400ms of overhead. In this article we were able to bring that down to ~22ms.

TIL fancy methods to transform Javascript Objects

You can use Object.entries(), Object.keys(), Object.fromEntries()...

TIL how to hide your JS code

ONE THING TO NOTE: Encrypting a script is stronger than obfuscation, both methods are still not adequate to protect secret content. Honestly, I don't think it's worth it on a production site, and instead just go with pure server-side if you want security. But it's fascinating.