DEV Community

Satel
Satel

Posted on

Explain Memoization in a pure Javascript

Memoization is the process of caching the output of function calls so that subsequent calls are faster. Calling the function again with the same input will return the cached output without needing to do the calculation again.

Because JavaScript objects behave like associative arrays, they are ideal candidates to act as caches. Each time a memoized function is called, its parameters are used to index the cache. If the data is present, then it can be returned, without executing the entire function. However, if the data is not cached, then the function is executed, and the result is added to the cache.

A basic implementation in Javascript looks like this:

const memoize = fn => {
  const cache = new Map()
  return value => {
    const cachedResult = cache.get(value)
    if (cachedResult !== undefined) return cachedResult
    const result = fn(value)
    cache.set(value, result)
    return result
  }
}
Enter fullscreen mode Exit fullscreen mode

Note

  • The above technique returns a unary function even if the function can take multiple arguments.
  • The first function call will be slower than usual because of the overhead created by checking if a cached result exists and setting a result before returning the value.
  • Memoization increases performance on subsequent function calls but still needs to do work on the first call.

Top comments (0)