Memoization In JavaScript Explained
JavaScript
07/06/2021
Memoization is a word you'll hear from time to time in JavaScript, especially if you use a library like React. It simply means memorizing, aka caching, the result of a function - the same way your browser 🧭 might cache the results of a GET request.
The benefit is quite straightforward: you improve performance by not running the same process twice. However, as you'll soon see, premature optimization isn't recommended.
Memoizing a function
Imagine you want to retrieve the h1
title of a page.
function getTitle() { return document.getElementById('heading').text}
It could be that you plan on calling this function many times, so you get the idea to cache the return value.
let cache = {}
function getMemoizedTitle() { if (cache['heading']) return cache['heading'] const titleValue = document.getElementById('heading').text cache['heading'] = titleValue return titleValue}
The memoized function first checks whether we already computed the result once before. If that is the case, we retrieve it and skip the rest of the function. If not, we proceed to retrieve the h1
title and store it in our cache
object.
Premature optimization
Just because you can, doesn't mean you should memoize a function. In fact, our memoized function is less performant than the regular function! 😱
I've even prepared a Codepen snippet which tests the performance of both functions when run twice. What you'll notice is that most of the time, our memoized function is slower.
Be sure to perform the Codepen test in a Chromium-based browser as other browsers (to my knowledge) don't return time in fractions of a millisecond.
The reason
There's always a cost associated with memoization, which stems from the extra lines of code. In our case, the getTitle
function wasn't computationally heavy to begin with. Therefore, the extra cost 💸 of optimization was greater than the potential amount of resources saved.
When To Use
As a rule of thumb, you should only apply memoization on a function that has become noticeably expensive to perform. Regex calls and recursions are part of that as well.
Likewise, this principle can be applied in JavaScript libraries/frameworks where memoization is prevalent (e.g. React).