Sunday, January 16, 2011

Multiplication vs division

AS3 is definitely not a language for number crunching, but simple (or a little more complex) math is always with us.
When I look the places to improve performance of my code I never forget about readability of my code. This is why I'm not a fan of using bitwise operators (which are faster than multiplication and division) in my code because when working in a team, code clarity and maintainability is critical. But how about more "popular" operators like division and multiplication? Which operator is faster? Let me show the test results:

private function divisionAndMultiplicationPerformance():void
{
  var initialTime:int;
  var time:int;
  var i:int;
  const repCount:int = 1000000000;
  
  initialTime = getTimer();
  for(i = 0; i < repCount; i++)
  {
    10 / 2;
  }
  time = getTimer() - initialTime;
  log("Division: " + time + "ms");
   
  initialTime = getTimer();
  for(i = 0; i < repCount; i++)
  {
    10 * 0.5;
  }
  time = getTimer() - initialTime;
  log("Multiplication: " + time + "ms");
}
Here are results:
Division Multiplication
2.1 Ghz Intel Core 2 Duo, Windows 7
Flash Player 10.1
2103ms 2096ms

As you can see, multiplication is slightly faster than division. Is that difference worth of rewriting all our divisions to multiplications? I don't think so, but if you're desperate for speed and performance in your project, you can try this out or even change them to bitwise operators (GOOD LUCK:))

2 komentarze:

Jackson Dunstan said...

The readability point is definitely very important and should absolutely be weighed against performance. You can always help out readability by commenting (e.g. "this divides by 1024"), but the regular operators are even more clear.

Also, I've mentioned before about multiplication/division/bit shifts taking about the same amount of time in my article on Operator Speed if you're interested in further reading on a bunch more operators' relative performance on various data types.

fastas3 said...

Thanks Jackson for your comment. It might look like I'm duplicating your blog entries but I never read this great post. You've covered so much about AS3 performance, that I think many my posts would have links to yours:D cheers

Post a Comment

 
Powered by Blogger