Take the 2-minute tour ×
Game Development Stack Exchange is a question and answer site for professional and independent game developers. It's 100% free, no registration required.

I am working on a game using libgdx and I have the following code that I want to optimize.

    Array<Bullet> enemyBullets = Enemy2.getEnemyBullets();
    for (Bullet bullet : enemyBullets) {
        c = bullet.getHitBox();
        debugRenderer.circle(c.x, c.y, c.radius, 5);            
    }

Basically I just have a big array of objects that I want to preform some action on and I am not sure if this is the best way to do it. I'm not sure if it would be better to use a pool or try to use an iterator instead. I am just not really familiar with these things and I need some help.

share|improve this question

3 Answers 3

up vote 3 down vote accepted

If you follow this guide: http://developer.android.com/training/articles/perf-tips.html

Your method is the best approach, just remember to call the array from a reference that is in the same scope as your loop. Also, if possible, remove the "getHitBox" method, and get the object through public variables. Yes, this is ugly, but can be used in performance critical region for a small boost...

share|improve this answer

I think a general rule of most languages is that something like this is faster (not necessarily safer):

int count = enemyBullets.size;
for(int i=0;i<count;i++) {
    c = enemyBullets[i].getHitBox();
    debugRenderer.circle(c.x, c.y, c.radius, 5);
}

But it doesn't account for the fact that your collection could change inside the block.

For doing something like debugging, is this a considerable issue? Obviously, you wont run the debug renderer in your final game but for what you are debugging, is the for loop you're using causing issues?

share|improve this answer
    
In Android, your loop is not the fastest –  Zhen Dec 21 '12 at 8:32

Reverse your loop:

for (int i = enemyBullets.size - 1; i >= 0; i--) {
c = enemyBullets[i].getHitBox();
debugRenderer.circle(c.x, c.y, c.radius, 5);
}

The check 'i >= 0' is faster because it doesn't need to load the variable that holds the size, for each iteration.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.