DEV Community

loading...
Cover image for JS interview in 2 minutes / Memoization 💭

JS interview in 2 minutes / Memoization 💭

Nikita Kozlov
Make things happen ✨ Webdev / websec / management / drawing
・2 min read

Question:
What is memoization?

Quick answer:
It is a way to optimize application performance by caching results of time-consuming pure functions calculations.

Longer answer:
As we know from the previous post, there are pure and impure functions.

Pure functions are basically functions that return the same result if you pass the same data and they don't change anything outside of its scope.

let pureAdd = (a, b) => a + b
Enter fullscreen mode Exit fullscreen mode

This pureAdd function doesn't change anything outside it just returns the answer and it always returns the same answer for the same arguments.

With these restrictions come the benefits. If the result is the same every time we run the functions, then why don't we just calculate it once and save the result?

// Don't reuse it, it is just an example
let memo = (func) => {
  let cache = {}
  return (...args) => {
    if (cache[args]) {
      console.log('Cache hit :)')
      return cache[args]
    }
    console.log('Cache miss :(')
    let result = func(...args)
    cache[args] = result
    return result
  }
}

function sleep(ms) {
  var start = new Date().getTime(), expire = start + ms;
  while (new Date().getTime() < expire) { }
  return;
}

let slowAdd = (a, b) => {
  sleep(1000)
  return a + b
}

let memoAdd = memo(slowAdd)
console.log(memoAdd(1, 2))
// * waiting for 1 sec *
// Cache miss :(
// 3
console.log(memoAdd(1, 2))
// No waiting
// Cache hit :)
// 3
Enter fullscreen mode Exit fullscreen mode

Real-life applications:
It's not only a theoretical benefit but actually a practical one.

For example, there is React.memo which does memoization.

If your component renders the same result given the same props ... React will skip rendering the component, and reuse the last rendered result.

Also, there is a useMemo hook, which also does memoization.

useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render.

Resources:
wiki/memoization
react-docs

Other posts:


Btw, I will post more fun stuff here and on Twitter. Let's be friends 👋

Discussion (2)

Collapse
hasnaindev profile image
Muhammad Hasnain • Edited

Nice post. It was really eye opening for me when I realized that caches are more or less, simple key value pairs. One of the things that made me realize that I don't have to be scared of complex/big names.

Collapse
rohithv07 profile image
Rohith V

Dynamic programming :)