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
lol @ conclusion!
ReplyDeleteReally, 30x faster!? I would have never guessed.
ReplyDeletewoohoo! 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