Rashi Chouksey

Memorization Technique in JS

Introduction

So as our application grows and begins to carry out heavy contributions, You will need to optimize speed to your application. It should be faster so that your application can handle lots of users. If we ignore this concern, we end up with a program that takes lots of time during execution.

What is Memorization?

Memorization is an optimization technique that improves the performance of your application by storing the result from expensive function calls and returning cased results when the same input is applied again.

So it is clear to us that the aim of Memorization is to reduce the time taken and amount of resources consumed at the time of “expensive function execution”.

What is an expensive function call?

Expensive function means in the context of a computer there are two major resources: time and memory, when an expensive function calls the function consumes huge chunks of these resources during the execution time due to heavy computation. 

The Memorization uses caching to store the result of our function calls for quick and easy access for later time.

A cache simply temporarily stores data that holds data so that when a request for data they serve faster.

Why is memorization important?

Here is an example of memorization, it will show the importance of memorization. 

So just imagine you are in a park and reading a book that is pretty attractive cover, Each time a person passes by, they are drown by the cover, so they ask for the which book is this and who is the author, you trund the cover and read out title and name of author, so now more and more people come and ask same questions.

Would you like to read the book title and author again and again or you will answer them with your memory which saves you more time.

Notice the similarities? With memorization, when a function provides an input, it is required to compute and store the result in cache before returning the value, if the function will get the same input in future the output will come from cache (Memory).

It’s pretty simple, let’s understand how it works.

How does memorization works

A function are a virtual building block in any programming language, As a developer, you will often use a function in your project, One more important aspect of a function that should reusable, They can call anywhere in your project,

A function can return other functions or take a function as its argument.

Returning functions from functions

A function that operates on other functions, either by taking as an argument or by returning theme, Are also called higher order functions.

Lets see Memorization in Practice 

Simple function

function sum(a, b, c){
      console.log('Actual function call');
      return a + b + c;
  }
  const a = 1;
  const b = 2;
  const c = 3;
        
  console.log(sum(a, b, c))
  console.log(sum(a, b, c))
  console.log(sum(a, b, c))

  //Results:-
  Actual function call
  6
  Actual function call
  6
  Actual function call
  6

So in above code snapit i have used a simple function name is sum and passed 3 parameters and returned them, and outside the function i have a 3 variable  and then simple i have executed sum function inside the console and passed variables that’s it, Now see the results every time executing actual function. That’s why we use the memorization function. If the function’s argument is the same then do not call the actual function print the value from memory and cache.

Memorization function

<script>
    
   function sum(a, b, c){
       console.log('Actual function call');
       return a + b + c;
    }
    

    const a = 1;
    const b = 2;
    const c = 3;
        
    
    // console.log(sum(a, b, c))
    // console.log(sum(a, b, c))
    // console.log(sum(a, b, c))

    const memo = new Map();
    const memoizeFunc = (func) => {
       const memoizedF = (...args) => {
          const memokey = args.toString()
          if(memo.has(memokey)){
             console.log('Result from Memo');
             return memo.get(memokey);
          }else{
             const funcReturn = func.apply(null, args);
             memo.set(memokey, funcReturn);
             return funcReturn
          }
       }

       return memoizedF;
    }

    const memoizeSum = memoizeFunc(sum);
        
    console.log(memoizeSum(a, b, c));
    console.log(memoizeSum(a, b, c));
    console.log(memoizeSum(a, b, c));

    //Result:
     Actual function call
      6
      Result from Memo
      6
      Result from Memo
      6


</script>

So the sum function is our actual function and memoizeFunc is our memorization function.

So let’s see what’s going on in the function and how it’s working?

For memorization you will have to create a store where you can store your data i have created memo storage area in this memo i am storing all data with keys and value, memorization is all about key and value we can set data and get data with key, Now i have created function memoizeFunc with parameter func inside this function i have created another function named memoizedF with parameter …arge (destructuring) and inside this function i am working with the logic if and else condition if memo has memokey then print result from memo else go in else part and inside else condition am using apply method and set method for setting key and value to memo store.

Now outside all function i am executing main function memoizeFunc and passing sum function as a argument that’s way it’s working now simple consoled and see result,

Only the first time executing the actual function, second and third time showing the result from memo because of memorization.

Share