No announcement yet.

What is memoization

  • Filter
  • Time
  • Show
Clear All
new posts

  • What is memoization

    What is memoization

  • #2

    Memoization is a programming technique which attempts to increase a function’s performance by caching its previously computed results. 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. Otherwise the function is executed and then the result is added to the cache. Let's take an example of adding function with memoization,

    const memoizAddition = () => {
    let cache = {};
    return (value) => {
    if (value in cache) {
    console.log('Fetching from cache');
    return cache[value]; // Here, cache.value cannot be used as property name starts with the number which is not a valid JavaScript identifier. Hence, can only be accessed using the square bracket notation.
    else {
    console.log('Calculating result');
    let result = value + 20;
    cache[value] = result;
    return result;
    // returned function from memoizAddition
    const addition = memoizAddition();
    console.log(addition(20)); //output: 40 calculated
    console.log(addition(20)); //output: 40 cached


    • #3
      The concept of memoization in Javascript is backed by two main sub-concepts: Closure and High order function. In JavaScript, closures are generated every time a function is created and it allows you access to the domain of the outer function from the inner function. A high order function accepts another function as an argument or returns a function as its output.

      This technique is specially useful when it comes to dynamic programming. A memoized function is usually faster because if the function is called subsequently with the previous value(s), then instead of executing the function, would be fetching the result from the cache .


      Related Topics