# 按位运算代替乘、除和取模：哪个更快？

```// Multiplication
i * 8; // normal
i << 3; // bitwise [8 = 2^3, so use 3] // Division i / 16; // normal i >> 4; // bitwise [16 = 2^4, so use 4]

// Modulus
i % 4; // normal
i & 3; // bitwise [4 = 1 << 2, apply ((1 << 2) - 1), so use 3]
```

```package
{
import flash.display.*;
import flash.utils.*;
import flash.text.*;

public class FasterDivMod extends Sprite
{
private var __logger:TextField = new TextField();
private function row(...cols): void
{
__logger.appendText(cols.join(",")+"\n");
}

public function FasterDivMod()
{
stage.align = StageAlign.TOP_LEFT;
stage.scaleMode = StageScaleMode.NO_SCALE;

__logger.autoSize = TextFieldAutoSize.LEFT;

init();
}

private function init(): void
{
var beforeTime:int;
var afterTime:int;
var i:int;
var REPS:int = 100000000;
var absInt:int;

row("Method", "Time");

beforeTime = getTimer();
for (i = 0; i < REPS; ++i)
{
absInt = i / 4;
}
afterTime = getTimer();
row("Div: i / 4", (afterTime-beforeTime), absInt);

beforeTime = getTimer();
for (i = 0; i < REPS; ++i) { absInt = i >> 2;
}
afterTime = getTimer();
row("Div: i >> 2", (afterTime-beforeTime), absInt);

beforeTime = getTimer();
for (i = 0; i < REPS; ++i)
{
absInt = i * 4;
}
afterTime = getTimer();
row("Mul: i * 4", (afterTime-beforeTime), absInt);

beforeTime = getTimer();
for (i = 0; i < REPS; ++i)
{
absInt = i << 2;
}
afterTime = getTimer();
row("Mul: i << 2", (afterTime-beforeTime), absInt);

beforeTime = getTimer();
for (i = 0; i < REPS; ++i)
{
absInt = i % 4;
}
afterTime = getTimer();
row("Mod: i % 4", (afterTime-beforeTime), absInt);

beforeTime = getTimer();
for (i = 0; i < REPS; ++i)
{
absInt = i & 3; // ((1 << 2) - 1) == 3
}
afterTime = getTimer();
row("Mod: i & 3", (afterTime-beforeTime), absInt);
}
}
}
```

• Flex SDK (MXMLC) 4.6.0.23201, compiling in release mode (no debugging or verbose stack traces)
• Release version of Flash Player 11.3.300.271
• 2.3 Ghz Intel Core i7
• Mac OS X 10.8.0