5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

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...

\$\endgroup\$
1
\$\begingroup\$

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.

\$\endgroup\$
0
\$\begingroup\$

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?

\$\endgroup\$
  • \$\begingroup\$ In Android, your loop is not the fastest \$\endgroup\$ – Zhen Dec 21 '12 at 8:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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