Home arrow Blog arrow x*x is faster than Math.pow(x, 2) in ActionScript
x*x is faster than Math.pow(x, 2) in ActionScript Print E-mail
Wednesday, 07 February 2007

Just found out that x*x is about 78% faster than Math.pow(x, 2) in ActionScript (Flash 8, Windows)

In case you want to test it for yourself, here's some sample code:

var sq;
var t0, t1, tt, tp;

t0 = getTimer()
for (var i = 0; i < 100000; i++){
    sq = i*i;
}
t1 = getTimer()
tt = t1-t0;
trace ("* : "+ tt);


t0 = getTimer()
for (var i = 0; i < 100000; i++){
    sq = Math.pow(i, 2);
}
t1 = getTimer()
ts = t1-t0;
trace ("^ : "+ ts);
trace ("*/^ : "+ (tt/ts*100) + "%");

Comments
this is not surprise. Math.pow uses a generic algorithm that works for any exponent, including non-integers etc.
  Posted by michal, on Wednesday, 07 February 2007 at 3:17

You're right :). But in my case ( f8 and Windows, too ) it is about 65-67 % faster. How about that?
  Posted by sema, Whose homepage is http://szemraj.eu on Wednesday, 07 February 2007 at 3:19

Some C/C++ compilers do all kinds of optimization for you. I was kinda hoping Flash would do that too. But I guess not.
  Posted by Johan van Mol, on Wednesday, 07 February 2007 at 4:37

For Math.pow() to support variable powers, it has to use logarithmic functions, which are way slower than multiplication functions.
  Posted by Randy Edmunds, on Wednesday, 07 February 2007 at 11:28

You mean 22% right.

if x*x takes 366msec and Math.pow takes 477msec. then x*x must be 22% faster than Math.pow

x*x use only 78% of the time that Math.pow uses

  Posted by Klaus, on Friday, 28 September 2007 at 3:42


 1 
Page 1 of 1 ( 5 comments )
©2005 MosCom

Add your comments to this article x*x is faster than Math.pow(x, 2) i... ...

Name (required)

E-Mail (required)
Your email will not be displayed on the site - only to our administrator
Homepage

Comment