Updating multiple Sprites - AS3 performance best practices
Within the container "BubbleContainer" I have multiple "Bubble sprites". Each bubble's graphics object (a circle) is updated on a timer event.
Let's say I have 50 Bubble sprites and each circle's radius should be updated with a mathematical formula. How do I organize this logic?
How do I update all Bubble sprites within the BubbleContainer? (should I call a bubble.update() function o开发者_开发技巧r make a temporary reference to the graphics object?)
Where do I put the Math logic? (as static functions?)
If I were you I would worry more on how to efficiently do the Math rather than passing the data around because there you loose a big amount of time.
My advice on this would be:
Do all the calculation on the BubbleContainer (or anywhere else, but in one place rather than inside each object)
Precalc things like Math.PI/180
Precalc 2 arrays/vectors of sine and cosine values.(It's faster to get
them from an array rather than
calling Math.sin/Math.cos each time )Pass the result to the Bubble sprite in 1 call ( as Cristi pointed out )
Create a function that accepts input parameters , does all the math and returns the answer.
For each set of input( on each cal of this function ):
First see if the answer was calculated before, if it was retrieve it from the answer dictionary.
if not calculate it and add it to the answer dictionary.
Create an entry in a dictionary that has the input values as the key and the answer as the value. This way you are creating a cache of answers. For complicated,recurring calculations with a relatively small number of input parameters(as in your situation) it's faster to retrieve answer that you already calculated from a dictionary rather than doing the calculation again. If you'll use an array instead of a dictionary I believe it's going to be even faster..
Quick example, not optimized, just to give you an idea:
function multiply(x:int,y:int):int{
var retValue:int;
var key:String=String(x)+String(y);
if (answers[key]){ retValue=answers[key];}
else{ retValue=x*y; answers[key]=retValue;}
return retValue;
}
Put as few calls as possible. Static i heard is slower than class methods.
精彩评论