nemoblog

Archive for September, 2010

Math.abs()…where must be a faster way

by on Sep.24, 2010, under flash performance

Math.abs() is handy to use…but it´s quite slow. Here is a significant faster alternative (about one-third faster):

var test:Number = 0.0;
var sum:Number = 0.0;
var i:int;
var duration1:int = 0;
var duration2:int = 0;
var diffPercent:Number = 0.0;
var loopCount:int = 5000000;
var startTime:int;
startTime = getTimer();
for (i = 0; i < loopCount; ++i) {
	test = i * -1;
	sum += Math.abs(test);
}
duration1 = getTimer() - startTime;
trace(duration1 + " - " + sum);
sum = 0.0;
startTime = getTimer();
for (i = 0; i < loopCount; ++i) {
	test = i * -1;
	sum = (test < 0) ? sum - test: sum + test;
}
duration2 = getTimer() - startTime;
diffPercent = Math.round(duration2 / duration1 * 10000) / 100;
trace(duration2 + "(" + diffPercent + "%) - " + sum);

Results:

926 - 12499997500000
581(62.74%) - 12499997500000

Any ideas to further improve that?

Leave a Comment more...

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Blogroll

A few highly recommended websites...

    Archives

    All entries, chronologically...