Optimizing Math.floor() method by using int() function
To round down a positive number, the int() function is much faster than the Math.floor() method.
http://wonderfl.net/c/tTHN
However their results are different for negative numbers. Therefore, custom function is defined to get the same results as the Math.foor() method by using the int() function.
/**
* Copyright Fumio ( http://wonderfl.net/user/Fumio )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/gAgx
*/
package {
import flash.display.Sprite;
import flash.utils.getTimer;
import flash.text.TextField;
import flash.text.TextFieldAutoSize;
import flash.text.TextFormat;
import flash.text.TextFormatAlign;
[SWF(width = "240",height = "180")]
public class OptimizingFloor extends Sprite {
private const AMOUNT:uint = 5000000;
private var myVector:Vector.<Number> = new Vector.<Number>(AMOUNT);
private var my_txt:TextField = new TextField();
private var label_txt:TextField = new TextField();
private var my_fmt:TextFormat = new TextFormat();
public function OptimizingFloor() {
// Creating a TextField for display
createTextField();
createNumbers();
warmingUp();
// Starting Test
testMath();
test_int();
}
private function testMath():void {
var _vector:Vector.<Number> = myVector;
var nAmount:uint = _vector.length;
var started:int = getTimer();
for (var i:uint = 0; i < nAmount; i++) {
var n:Number = _vector[i];
var m:int = Math.floor(n);
}
xTrace("Math.floor()", getTimer() - started);
}
private function test_int():void {
var _vector:Vector.<Number> = myVector;
var nAmount:uint = _vector.length;
var started:int = getTimer();
for (var i:uint = 0; i < nAmount; i++) {
var n:Number = _vector[i];
var m:int = xFloor(n);
}
xTrace("using int()", getTimer() - started);
}
private function xFloor(n:Number):int {
var i:int = int(n);
if ((n < 0) && (i != n)) {
--i;
}
return i;
}
private function warmingUp():void {
var _vector:Vector.<Number > = myVector;
var nAmount:uint = _vector.length;
var started:int = getTimer();
for (var i:uint = 0; i < nAmount; i++) {
var n:Number = _vector[i];
}
var temp:uint = getTimer() - started;
}
private function createNumbers():void {
var nAmount:uint = AMOUNT;
var nRange:Number = 10;
var nHalf:Number = nRange / 2;
for (var i:uint = 0; i < nAmount; i++) {
myVector[i] = Math.random() * nRange - nHalf;
}
}
private function createTextField():void {
addChild(my_txt);
addChild(label_txt);
my_fmt.align = TextFormatAlign.RIGHT;
// my_txt.x += 20;
my_txt.defaultTextFormat = my_fmt;
my_txt.autoSize = TextFieldAutoSize.RIGHT;
label_txt.autoSize = TextFieldAutoSize.LEFT;
}
private function xTrace(_str:String,n:int):void {
my_txt.appendText(String(n) + "\n");
label_txt.appendText(_str + ":" + "\n");
}
}
}