Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I had to look up what memoization is- guess I’m getting rusty? But it turns out it’s just a new word for an old concept (caching).

I’ve always done it this way:

double calculation(double arg) {

  thread_local bool prev_arg_valid = false;
  thread_local double prev_arg;
  thread_local double prev_result;

  double result;
  if(prev_arg_valid && prev_arg == arg)
    result = prev_result;
  else {
    //do the calculation 
    result = ...;
    prev_arg = arg;
    prev_result = result;
    prev_arg_valid = true;
  }
  return result;
}

Doing it this way is something you would only ever do if you knew beforehand the user would be asking for the same value over and over, but it’s clean and invisible to the calling code and doesn’t break your assumptions about what the function is going to return.

The memoization pattern is valid too of course, I just find it interesting I’ve always done the same thing when advantageous but in a different way.



> I had to look up what memoization is- guess I’m getting rusty? But it turns out it’s just a new word for an old concept (caching).

The term memoization was coined in 1968 and quite possibly predates the term cache (with respect to computing).


Interesting!

I still maintain though that memoization is a special case of caching with n=1. :)




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: