Shift Right ( >> )
When you need to divide a number by 2 or its power we can instead use shift operator. You read more about the theory behind it elsewhere, say wikipedia.
//shift right ( divide )Shifting right by one position is similar to divide by 2, and shifting right by two position is similar to divide by 4.
trace( 12 >> 1 ); //6
trace( 12 >> 2 ); //3
//shift left ( multiply )
trace( 12 << 1 ); //24
trace( 12 << 2 ); //48
Similarly, is the case with shift left ( << ) where you will be multiplying the value instead.
// bit shift vs divide operator performanceThis shows that the bit wise operators perform better than multiplication or division operators. This is tested using the debug version of the flash player. Using the normal version might show better results.
var bigNum:int = 100000000; //8-zeros
var i:int=0;
function computeDiv():void
{
for( i=0; i<100000000; i++ ) {
bigNum = bigNum / 2;
}
}
function computeShift():void
{
for( i=0; i<100000000; i++ ) {
bigNum = bigNum >> 1; //shift right
}
}
var t0:Number = getTimer();
trace( t0 ); //22
computeDiv();
var t1:Number = getTimer();
trace( t1 ); //4017
trace( "Time elapsed (Division): " + String( t1 - t0 ) ); //3995
var t2:Number = getTimer();
trace( t2 ); //4017
computeShift();
var t3:Number = getTimer();
trace( t3 ); //5689
trace( "Time elapsed (Shift): " + String( t3 - t2 ) ); //1672