Javascript Memoization with underscore

If you’ve not discovered the handy use of Memoization, I encourage you to look into it and take advantage. 

My Use case

So, I was generating a large UI on the client using knockout.  I had pre-loaded some “lookup data” (imagine id/name pairs in memory) that I’d repeatedly look up as I built a grid of sorts.  So, imagine having to do that lookup hundreds, or thousands of times, for only a handful of unique ids – thus repeating the calls a LOT!  This is where memoization shines.

The awesome underscore library has a simple implementation to use.  Here’s a simple bin which demonstrates the usage (note I put my own hasher in there, as the default hasher only keys off the first parameter to your routine – which you’ll see, is the same in my case for all 4 calls).

Leave a comment