Comparing two formulas to round a number to an integer
For positive numbers two formula can be used to round them to integers. This code compares their speeds.
[1] Math.round(number)
[2] int(number + 0.5)
/**
* Copyright Fumio ( http://wonderfl.net/user/Fumio )
* MIT License ( http://www.opensource.org/licenses/mit-license.php )
* Downloaded from: http://wonderfl.net/c/hEtj
*/
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 Rounding extends Sprite {
private const AMOUNT:uint = 10000000;
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 Rounding() {
// 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.round(n);
}
xTrace("Math.round(n)",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 = int(n + 0.5);
}
xTrace("int(n + 0.5)",getTimer() - started);
}
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;
for (var i:uint = 0; i < nAmount; i++) {
myVector[i] = Math.random() * nRange;
}
}
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");
}
}
}