I work on a team that has some really great developers. A few days ago in a PR review, I came across:
const formatNumberFull = memoize(number => numeral(number).format("0,0"));
Ummm... what? The Lodash docs gave me a little better understanding of what memoize
does, but I didn't really understand what was going on.
Here's the gist. Say you have an expensive operation that might be repeated frequently. Perhaps you're calculating factors. You don't want to have to perform that same operation over and over for the same number. Memoize effectively lets you cache the results of a function for the same arguments.
Trite Example:
function add(a, b) {
return a + b;
}
add(20, 5);
add(10, 10);
add(20, 5);
add(10, 10);
add(20, 5);
If add
were a really slow function, your app would needlessly come to a crawl. Instead of executing add
over and over, Memoize lets your app cache the results for the same arguments. If you call add
again with the same arguments, it returns the cached result instead of performing the expensive operation.
Memoize It
function add(a, b) {
return a + b;
}
var adder = _.memoize(add);
adder(20, 5);
adder(10, 10);
adder(20, 5);
adder(10, 10);
adder(20, 5);
The adder
"memoized" the add
function. Now, each time adder
is called, if the same arguments have been used, I'll get the results of the cache.
IMPORTANT: Thanks to Pavel Zubkou for pointing out something I completely missed about memoize
. By default, it only uses the first argument as the resolver. So, if you do adder(20,5)
you will of course get back 25
. However, if you later run adder(20, 500)
, you will unfortunately get back the same answer: 25
! Here's an example of this: https://codesandbox.io/s/lodash-memoize-75mpw. If you need to pass multiple arguments and get the right cache result, you can use a resolver to create the key for the cache. Here's an updated post with an example.
Here's a sample I put together that shows you exactly how to do this with a realistic scenario: