forked from: forked from: [最適化 Tips] Modulo vs Logical AND
forked from forked from: [最適化 Tips] Faster Math.sqrt? (diff: 36)
ActionScript3 source code
/**
* Copyright onedayitwillmake ( http://wonderfl.net/user/onedayitwillmake )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/q1As
*/
// forked from onedayitwillmake's forked from: [最適化 Tips] Faster Math.sqrt?
// forked from muta244's [最適化 Tips] 変数名の長さによる処理速度の違い
package {
import flash.display.*;
import flash.events.*;
import flash.text.*;
import flash.utils.*;
public class Main extends Sprite
{
static private const _NUM_TIMES :uint = 1000000;
static private var _isEven :Boolean;
private function _init():void
{
_debug(
"Math.sqrt vs custom function " + _NUM_TIMES + " cycles.\n"
);
_measure("Empty loop", function ():void
{
for (var i:uint = 0; i < _NUM_TIMES; i++) {
}
});
_measure("isEven with Modulo ( % )", function ():void
{
for (var i:uint = 0; i < _NUM_TIMES; i++) {
_isEven = (i % 2) == 0;
}
});
_measure("isEven with AND ( & )", function ():void
{
for (var i:uint = 0; i < _NUM_TIMES; i++) {
_isEven = (i & 1) == 0;
}
});
_debug("\n Using Logical AND is ~1000% faster than modulo.");
}
private var _field:TextField;
private var _time:uint;
public function Main():void
{
_setup();
_init();
}
private function _measure(title:String, func:Function, ...params):void
{
_time = getTimer();
func.apply(null, params);
_time = getTimer() - _time;
_debug("[ " + title + " ] --> " + _time + " ms");
}
private function _debug(log:String):void
{
_field.appendText(log + "\n");
}
private function _setup():void
{
_field = new TextField();
_field.width = stage.stageWidth - 40;
_field.height = stage.stageHeight - 60;
_field.x = 20;
_field.y = 60;
var format:TextFormat = _field.defaultTextFormat;
format.font = "_sans";
_field.defaultTextFormat = format;
addChild(_field);
var button:Sprite = new Sprite();
button.graphics.lineStyle(1, 0xBBBBBB);
button.graphics.beginFill(0xEEEEEE);
button.graphics.drawRoundRect(0, 0, 100, 20, 5, 5);
button.graphics.endFill();
addChild(button);
button.x = 20;
button.y = 20;
button.mouseChildren = false;
button.buttonMode = true;
var field:TextField = new TextField();
field.width = 100;
field.height = 20;
field.htmlText = "<p align='center'><font face='_sans'>Test Again</span></p>";
button.addChild(field);
button.addEventListener(MouseEvent.CLICK, function ():void
{
_field.text = "";
_init();
});
}
public static function FSQRT(val:Number):Number
{
var thres:Number = 0.002;
var b:Number = val * 0.25;
var a:Number;
var c:Number;
do
{
c = val / b;
b = (b + c) * 0.5;
a = b - c;
if (a < 0) a = -a;
}
while (a > thres);
return b;
}
}
}
