Pranjal Diwedi
Pranjal Diwedi

Reputation: 1178

Having hard time understanding memoization

Recently, I was reading 'The good parts' and was going through a topic called memoization but I couldn't understand it properly. What I did not get is, won't it be a memory consuming way like keeping a variable with a lot of data in case the function is executing a high number of time. If this is the case, than how is it optimization. Please note that, I am new to java script and I have read about this topic.

Upvotes: 0

Views: 258

Answers (3)

Rudra
Rudra

Reputation: 1688

Memoization is a simple mechanism that consist in caching the result of computed values.

  1. This allows the next function call, done with the same parameters, to hit the cache rather than re-computing this values.
  2. The cache is indexed by the input arguments. If the arguments exist in the cache, then the cached value is returned.
  3. Otherwise, the function is executed and the newly computed value is added to the cache.

If you understand the caching mechanism, it's very easy to understand memoization.

As far as I know, there are two level of optimizations one can do with their programme:

  1. Time Optimization
  2. Memory Optimization

It totally depends on the requirement.

Upvotes: 1

Sagar
Sagar

Reputation: 1335

If you know basics of

  • prototypal inheritance
  • variable scope and
  • closure

this article is what you need. but mind that you must be knowing JS concepts mentioned above

Upvotes: 0

Akash Tiwari
Akash Tiwari

Reputation: 11

Remember dynamic programming? While calculating the factorial of a number, you remember the factorial till n-1 and then multiply the fact(n-1) with n. But the problem in some cases is the unnecessary calls, which can easily be avoided.

To save these unnecessary calls, we can memoize it. To save the memoize results, one can use an array, inside a closure. When your function is called, first thing it checks is whether it already has an answer, if yes, then it returns the answer otherwise, it recalculates it.

Upvotes: 1

Related Questions