Tuesday, August 11, 2009

Switch vs. Array Index

At the last Javascript Meetup Cambridge I was showing off a Javascript Web Worker Network I have been working on for visualizing search queries. I showed the code to @geowa4, @AlbertoPL and another guy who's name I forget. @geowa4 pointed out that I could use look up the function directly from the object (which I had avoided thinking switch was faster), and someone else chimed in that the switch I was already using would be faster... and I was like... "yeah, get back in your place student n00b!"

Obviously... this had to be tested!

var obj = [];
var len = 10;
for( var i = 0; i < len; i++ ){
obj[i] = function(){ return 1 };
}
obj[ 10 ] = function( mn, inc ){
time = new Date().getTime() - time;
console.log( 'Method #' + mn + ': ' + time + 'ms, Check: ' + ( inc == 20000000 ) );
};

var time;
var times = 2000000;

function method1(){
time = new Date().getTime();
var inc = 0;
for( var t = 0; t < times; t++ ){
for( var i = 0; i < len; i++ ){
inc += obj[ i ]();
}
}
obj[ 10 ]( 1, inc ) ;

// run next method
method2();
}

function method2(){
time = new Date().getTime();
var inc = 0;
for( var t = 0; t < times; t++ ){
for( var i = 0; i < len; i++ ){
switch( i ){
case 0: inc += obj[0](); break;
case 1: inc += obj[1](); break;
case 2: inc += obj[2](); break;
case 3: inc += obj[3](); break;
case 4: inc += obj[4](); break;
case 5: inc += obj[5](); break;
case 6: inc += obj[6](); break;
case 7: inc += obj[7](); break;
case 8: inc += obj[8](); break;
case 9: inc += obj[9](); break;
}
}
}
obj[ 10 ]( 2, inc );
}

method1();


The results:
ARRAY --> Method #1: 257ms, Check: true
SWITCH --> Method #2: 7344ms, Check: true

Congratulations @geowa4 wins! IOU 1 beer.


Conclusion:
Never under-estimate the student n00b. Even if they don't know what they're talking about... they're probably still right. XD

3 comments:

  1. lol @ conclusion!

    ReplyDelete
  2. Really, 30x faster!? I would have never guessed.

    ReplyDelete
  3. woohoo! free beer! i'm not one to say no to that. switch statements are bad for many reasons IMO. for one thing, they lead to unmaintainable code, which can greatly impact performance and development time in the future.

    ReplyDelete