Speeding up your JavaScript: Part 3 and 4

Nicholas C. Zakas wraps up his series on speeding up JavaScript with two more posts on the subject.

First up, he delves deeper into a generic memoizer:

In part 2 of this series, I wrote briefly about handling too much recursion in a function through memoization. Memoization is a technique for caching previously calculated values so that they need not be recalculated; when a recursive function is doing such a calculation, memoization is incredibly useful. The memoizer I presented was Crockford’s, and is useful primarily for recursive functions that return integers. All recursive functions, of course, don’t return integers. A more generic memoizer() function can be created to deal with any type of recursive function:

JAVASCRIPT:

  1.  
  2. function memoizer(fundamental, cache){
  3.     cache = cache || {}
  4.     var shell = function(arg){
  5.         if (!(arg in cache)){
  6.             cache[arg] = fundamental(shell, arg)
  7.         }
  8.         return cache[arg];
  9.     };
  10.     return shell;
  11. }
  12.  

Then he gets into other examples, and concludes:

The bottom line: always be on the look out for recursion in your JavaScript. Memoization and iteration are two ways to avoid excessive recursion and the long-running script dialog.

The final part of the series deals with the DOM, and looks at practices such as using DOMFragments instead of touching the live DOM (John Resig has been talking a lot about that):

JAVASCRIPT:

  1.  
  2. var fragment = document.createDocumentFragment();
  3. for (var i=0; i <items.length; i++){
  4.     var item = document.createElement(“li”);
  5.     item.appendChild(document.createTextNode(“Option “ + i);
  6.     fragment.appendChild(item);
  7. }
  8. list.appendChild(fragment);
  9.  

Go to Source

  • Digg
  • del.icio.us
  • Facebook
  • Google Bookmarks
  • LinkedIn
  • Live
  • MySpace
  • Print
  • StumbleUpon
  • Technorati
  • YahooMyWeb
  • Yigg
*Name
*Mail
Website
Comment