I have 6 objects that have to move randomly and continuously. Is it efficient to enterframe each object seperately or 1 enterframe with loop addressing all objects.
var myObjArray:Array = new Array(); // Contains 6 movieclip objects
for(var i=1; i<=6; i++)
{
var Square:MoveObject = new MoveObject();
Square.addEventListener(Event.ENTER_FRAME, Square.go);
myObjArray[i] = Square;
}
public Class MoveObject extends Movieclip{
public function go(e:Event):void
{
this.x++;
}
}
OR we loop through objects in one EnterFrame function ?
Every function call has a performance penalty – that’s why people talk about “inlining” functions in critical sections of code (inlining the function contents rather than making the function call).
The best case, then, is to add only 1 listener, and in that listener loop over all 6 objects. Another tip – if you iterate the loop in reverse, you only call the .length() function on the array once, whereas if you iterate from 0-length, the for loop must call the length function every time to determine if the condition is met.
There are surely other optimizations (some people say –i is faster than i–, but I’m not sure this is true for ActionScript).
Of course, at 6 objects, it’s not a huge deal, but if you scale that up, you’ll definitely want to use a single listener.