jsBenchmarker
Source of "loops"
Back
/**
* @html <p><b>warning:</b> the test is long.</p>
*/
var limit = 5e4, counter;
function action(){
--counter;
};
Benchmarker().compare({
attempts:10,
times:1,
onBeforeAttempt:function(){
counter = limit;
},
onAfterAttempt:function(){
if( counter < 0 )
alert('this one did too many');
else if( counter > 0 )
alert('this one did too few');
}
}, {
'for':function(){
for( var i = 0, times = limit; i < times; i++ )
action();
},
'while':function(){
var i = 0, times = limit;
while( i++ < times )
action();
},
do_while:function(){
var i = 0, times = limit;
do action();
while( ++i < times );
},
for_reversed:function(){
for( var i = limit; i; i-- )
action();
},
while_reversed:function(){
var i = limit;
while( i-- )
action();
},
while_reversed_left:function(){
var i = limit + 1;
while( --i )
action();
},
do_while_reversed:function(){
var i = limit;
do action();
while( --i );
},
duff:function(){
var loops = limit;
while ( loops )
switch( loops % 4 ){
case 0: action(); --loops;
case 3: action(); --loops;
case 2: action(); --loops;
case 1: action(); --loops;
}
},
duff2:function(){
var loops = limit,
rest = loops % 4;
while( rest-- )
action( --loops );
while( loops ){
action(); --loops;
action(); --loops;
action(); --loops;
action(); --loops;
}
},
duff3:function(){
var rest = limit % 4,
loops = (limit - rest) / 4;
while( rest-- )
action();
while( loops-- ){
action();
action();
action();
action();
}
}
});