documentcloud/underscore — pull request #330 by addyosmani (2011-10-09 11:56:58+00:00)
Title: Optimized replacement for _.memoize()

I took the work we've been doing on an optimal memoization routine in [1][2] and integrated it with underscore to offer an implementation which is both:

-significantly more performant than the current version
-supports more cases likely to be used in production
-passes the test suite tests for the old memoizer

The implementation in [2] comes with it's own tests in that repo, however what you're probably more interested in looking at are the performance figures. Here's a jsPerf test (others are available) which demonstrates the improvements in performance from the existing implementation when compared to this one:

http://jsperf.com/comparison-of-memoization-implementations/12

The work here has gone through multiple rounds of further optimization by @mathias, @dmitrybaranovskiy, Jamie Mason and others and is currently the fastest (thus benchmarked) memoizer we're currently aware of (as you'll see in the tests, we also compare against other implementations by John Hann, Thomas Fuchs etc).

The only real difference between the current approach and mine/ours is that the optional hash function is dropped. I've thoroughly reviewed use of memoization in JS projects out there at the moment and I haven't seen a great number of people actually rely on such optional functions, they just want the main memoizer itself.

It would be great if we could get this in Underscore, but definitely open to thoughts on whether it's worth including.

Notes:

The new memoizer has dependencies on JSON support being natively available. I think this is *okay* given that the current implementation requires the use of hasOwnProperty which has known issues with IE6, but we're happy to spend more time on support issues if needed.

You may also ask whether the perf test is a fair comparison of access/usage times. We've also separately benchmarked these in the earlier stages of development with the newer implementation outperforming the others there too. Happy to create another test to demonstrate if needed.

Thanks!

Refs:

[1] http://addyosmani.com/blog/faster-javascript-memoization/
[2] https://github.com/addyosmani/memoize.js
[3] http://jsperf.com/comparison-of-memoization-implementations/12