beyond applications and software

JavaScript summed up #9: Memoization

Doing the same work twice is never a good thing. Knowing that, a pattern called “Memoization” can help you avoid this. It’s about building functions that remember their previous outputs/return values.

Let’s pretend you’ve written a function that takes a number as an argument and multiplies it with, say, 2.5. Not exactly heavy computational work, but for the sake of clearness…

var multiplierFunction( myNumber ) {
    return myNumber * 2.5;
}

If you call the function 10 times, it will have to do the computation 10 times. In cases where there’s some more effort inside the function, this can be a waste of performance.

To reimplement it using memoization, you just need to provide a plain JavaScript object that remembers previous results. Here, we call it “memo” and attach it right to the function:

multiplierFunction = function( myNumber ){
    if ( typeof multiplierFunction.memo[myNumber] != "undefined" ){
         return multiplierFunction.memo[myNumber];
    }
    // the following code will only be executed if necessary
    // i.e. if the same calculation wasn't done before
    multiplierFunction.memo[myNumber] = myNumber * 2.5;
    return multiplierFunction.memo[myNumber];
}
multiplierFunction.memo = {};
Share this:
  • Print
  • email
  • PDF
  • Twitter
  • Digg
  • del.icio.us
  • MisterWong
  • StumbleUpon
  • Facebook
  • Netvibes
  • Google Bookmarks
  • FriendFeed
  • Mixx
  • Live
  • Ping.fm
  • Technorati
  • Yigg

1 comment

1 Sam Müller { 10.01.09 at 10:36 am }

Hi Tobi – This is really good stuff. You can use this in your real life too. ;-) Samster

Leave a Comment