0

I was recently looking into a few javascript design patterns and came across memoization while it looks like a good solution to avoid recalculation of values i can see something wrong with it. say for example this simple code,

function square(num)
{
  var result;
  if(!square.cache[num]){
     console.log("calculating a fresh value...");
     result = num*num;
     square.cache[num] = result;
  }
  return square.cache[num];
}
square.cache={}

calling console.log(square(20)) //prints out "calculating a fresh value..." and then the result of the calculation 400,

My real question is what happens when the cache grows so large after subsequent calculations that it takes more time to retrieve a result from the cache than it takes to calculate a fresh value. is there any solution towards this?

3
  • 1
    The solution is to not use memoization. It's very rare to use it, for a reason. If your cache might be very large and it still makes sense to use a cache, use a proper one (for example a LRU cache) Commented Apr 16, 2014 at 9:13
  • It is a fairly straight forward program, you can do calculation directly. I would say you are abusing memoization technique here ;) Commented Apr 16, 2014 at 9:23
  • Lol @thefourtheye, this is just a simple illustration of my curiosity. i am applying this in a much complex and broader scenario in my project. Commented Apr 16, 2014 at 9:32

1 Answer 1

1

My real question is what happens when the cache grows so large

This is where you would implement a sort of Garbage Collection. Items could be removed from the cache following a Cache Algorithm.

So for example following Least Recently Used you would record how many times a specific object was used when it was last accessed and remove those from the cache that were not used recently.

Edit

Soundcloud use an object store and a very interesting read is this article on how they built their webapp.

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks gimg1 for the extra info. that was very helpful.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.