JavaScript Memoization
Posted on February 25th, 2009 in JavaScript | 1 Comment »
I was taking a look at my friend Takashi’s JavaScript tweener which isn’t released yet and noticed he setup his code in a particular way for a few methods that get called dozens of times a second. He explained to me that it was for optimization through memoization. I ran a test case, and indeed it’s much faster. Check it out:
a = {}; a.deep = {}; a.deep.variable = { here: 3 } function plain(){ document.body.appendChild(document.createTextNode(a.deep.variable.here)); } function memoized(){ var z = a.deep.variable.here; return function(){ document.body.appendChild(document.createTextNode(z)); } } now = new Date(); for (var i = 0, max = 5000; i < max; i++){ plain(); } alert(new Date() - now); now = new Date(); for (var i = 0, max = 5000; i < max; i++){ memoized(); } alert(new Date() - now); // plain: 759 // memoized: 36
There’s a more complex example on the subject posted a month ago on Ajaxian and an easier to understand one on Oliver Steele’s blog written back in 2006.