Activate your free membership today | Log-in

Friday, January 23rd, 2009

Speed up your JavaScript with memoization and queueing

Category: JavaScript, Performance

<>p>Nicholas C. Zakas is back at it with part two of his Speed up your JavaScript series.

This time he again discusses the problem with loops, and in this case nested loops:

JAVASCRIPT:
  1.  
  2. function bubbleSort(items){
  3.     for (var i=items.length-1; i>= 0; i--){
  4.         for (var j=i; j>= 0; j--){
  5.             if (items[j] <items[j-1]){
  6.                 var temp = items[j];
  7.                 items[j] = items[j-1];
  8.                 items[j-1] = temp;
  9.             }
  10.         }
  11.     }
  12. }
  13.  

What can you do to minimize the steps? He first talks about splitting it up asynchronously, and then goes into Doug Crockfords memoizer function, applying it to the standard Fibonnaci:

JAVASCRIPT:
  1.  
  2. function memoizer(memo, fundamental) {
  3.     var shell = function (n) {
  4.         var result = memo[n];
  5.         if (typeof result !== 'number') {
  6.             result = fundamental(shell, n);
  7.             memo[n] = result;
  8.         }
  9.         return result;
  10.     };
  11.     return shell;
  12. };
  13.  
  14. var fibonacci =
  15.     memoizer([0, 1], function (recur, n) {
  16.        return recur(n - 1) + recur(n - 2);
  17.     });
  18.  

Finally, he attacks functions that just do too much, and kicks off the pieces so the browser can get back to its work:

JAVASCRIPT:
  1.  
  2. function schedule(functions, context){
  3.     setTimeout(function(){
  4.         var process = functions.shift();
  5.         process.call(context);
  6.  
  7.         if (functions.length> 0){
  8.             setTimeout(arguments.callee, 100);
  9.         }
  10.     }, 100);
  11. }
  12.  
  13. schedule([doSomething, doSomethingElse, doOneMoreThing], window);
  14.  

Of course, for serious workload, this is what Web Workers are ideal for. In fact I just saw a new post on using Workers in extensions that shows the API nicely.

Also, just in case you are going for a Google front end position and you want to marry JavaScript and algorithms, how about remembering binarySearch to go along with the earlier bubbleSort:

JAVASCRIPT:
  1.  
  2. Array.prototype.binarySearch = function binarySearch(find, comparator) {
  3.   var low = 0;
  4.   var high = this.length - 1;
  5.   var i, comparison;
  6.   while (low <= high) {
  7.     i = parseInt((low + high) / 2);
  8.     comparison = comparator(this[i], find);
  9.     if (comparison <0) { low = i + 1; continue; };
  10.     if (comparison> 0) { high = i - 1; continue; };
  11.     return i;
  12.   }
  13.   return null;
  14. };
  15.  

Related Content:

  • JavaScript Learning Guide
    This SearchDomino.com guide introduces you to JavaScript in a Notes/Domino environment, explains best practices and pitfalls to avoid and provides...
  • Google Chrome shifts architects' equations as V8 powers the browser
    The V8 JavaScript engine in Google's Chrome browser offers the enterprise architect new options for moving server-side functionality to the Web...
  • FAQ: Lotus Notes, Domino and JavaScript
    Caught in a JavaScript jam? Before posing a question to our SearchDomino.com experts, check out our list of frequently asked questions on JavaScript...
  • JQuery 1.4 goes live
    jQuery JavaScript library brings performance and coding improvements. This release represents a significant update to the...
  • Caching Scenarios
    Caching is a quick and easy way to save roundtrips between your application and where you store your data. However, it’s not as easy as just...

Posted by Dion Almaer at 6:03 am
6 Comments

+++--
3.4 rating from 13 votes

6 Comments »

Comments feed TrackBack URI

dejavu … and in my “Stressfull procedure? Distribute your task!” entry I implemented the delay and the in-line or propagated scope.
The result with the queue callbacks stack is a slower application that is more responsive instead of a “not that quick” one that is stuck till the end of the loop. As summary, a slower execution for a faster, non modal, interaction, sounds weird, doesn’t it? :D

Comment by WebReflection — January 23, 2009

Just out of interest, regarding the Zakas “schedule” example how would I pass parameters to each function.

Comment by doomedlung — January 23, 2009

I did a “more generic” version of a memoization function not so long ago, if someone’s interested.

http://blog.thejit.org/2008/09/05/memoization-in-javascript/

Comment by philogb — January 23, 2009

@ doomedlung: I tried creating a method for that. It accepts any number of arguments as long as those arguments has a string representation. If you can imporve it please let me know.

You can find it at http://www.jslab.dk/library/Function.memoize

Comment by Tavs — January 23, 2009

I like building the memoization right into the function, using the fact that a function is an object that can have properties.

Comment by Nosredna — January 23, 2009

Wow, takes me right back to Intro to Programming…nice.

Comment by mjuhl — January 26, 2009

Leave a comment

You must be logged in to post a comment.