2

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 ?

Muhammad
  • 425
  • 1
  • 6
  • 14

1 Answers1

4

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.

function enterFrame(e:Event):void
{
  for (var i:int=myObjArray.length-1; i>=0; i--) {
    myObjArray[i].x++;
  }
}

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.

Jeff Ward
  • 16,563
  • 6
  • 48
  • 57
  • 1
    You could also save away the length, and not have a weird backwards loop ;) – Jonatan Hedborg Nov 16 '12 at 16:30
  • @Jeff Ward , Gr8 reply. You said 6 objects is not a huge deal, is it same for Android devices. – Muhammad Nov 16 '12 at 16:35
  • 1
    Weird backwards loops also let you modify them on the fly - I've gotten quite used to them. :) @Muhammad - resources are always tighter on mobile - it's best to use every optimization trick in the book (Object pools, inline functions, single event handlers - especially for touch events). – Jeff Ward Nov 16 '12 at 17:54