Friday, October 22, 2010

Bitwise Shift Operator Performance

Bitwise shift operators ( shift left <<, and shift right >> ) can be used in multiplying and dividing if the divisor is a power of 2. Here I ran a test which shows that bitwise shift operators perform twice faster than the multiplication or division operators.

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 )trace( 12 >> 1 );    //6trace( 12 >> 2 );    //3//shift left ( multiply )trace( 12 << 1 );    //24trace( 12 << 2 );    //48`
Shifting right by one position is similar to divide by 2, and shifting right by two position is similar to divide by 4.
Similarly, is the case with shift left ( << ) where you will be multiplying the value instead.
`// bit shift vs divide operator performancevar bigNum:int = 100000000;    //8-zerosvar 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 );    //22computeDiv();var t1:Number = getTimer();trace( t1 );    //4017trace( "Time elapsed (Division): " + String( t1 - t0 ) );    //3995var t2:Number = getTimer();trace( t2 );    //4017computeShift();var t3:Number = getTimer();trace( t3 );    //5689trace( "Time elapsed (Shift): " + String( t3 - t2 ) );    //1672`
This 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.