2

Occasionally my game has hicups/dropped frames because of garbage collection. So I am trying to reduce this by removing unnessasary allocations.

Using the allocation tracker in Eclipse I see that my code below:

for (IGameObject obj : mObjects) {
  //stuff
}

Is allocating an iterator:

java.util.ArrayList$ArrayListIterator   24 bytes    java.util.ArrayList iterator

I can easily change all places where this is happening as mObjects is an ArrayList.

Just out of interest though, will proguard or jit somehow optimise this to a basic for loop? As it seems a shame I have to make my code more verbose to avoid this allocation.

2
  • 3
    Is it 24 bytes worth an optimization? even if you allocate it for 1000 times its only 23.5KB. I thinkyou should look at your graphics or other heavy objects! Commented Sep 30, 2012 at 9:58
  • 1
    @Tecigo As they say, it's not the size that counts. Garbage collection during the game causes hicups/dropped frames. Best solution is to remove unnessasary allocations, this is just one of many allocations I'm trying to remove. Commented Sep 30, 2012 at 12:39

2 Answers 2

1

Well, as people have said, don't optimize unless it's really an issue, but there's always:

int sz = mObjects.size();
IGameObject gameObject = null;
for (int i=0;i<sz;i++) {
    gameObject = mObjects.get(i);
}

In this case you're just looping through by index. For ArrayList this is pretty efficient (as efficient as an iterator probably from a speed standpoint). However, if you drop in a LinkedList at some point instead, it goes to hell for large lists, as .get(index) is terribly inneficient for LinkedList.

I would not worry about the extra 24 bytes unless you really have memory issues.

Sign up to request clarification or add additional context in comments.

Comments

0

The best way to control the memory consumption is to do the allocations yourself and in basic structures.

For example you could transform your ArrayList mObjects in a simple array IGameObject[] mObjects = new IGameObject[MAX_GAME_OBJECTS]; (you should know/compute what is the maximum number of objects your game can handle). In addition you should re-use the objects. You could keep an array boolean[] isObjAlive = new boolean[MAX_GAME_OBJECTS]; (same dimension as mObjects) and it will help in the first place to know which objects you no longer display and in the second, if the object is reusable:

 for(i=0;i<MAX_GAME_OBJECTS;i++){
    if(isObjAlive[i]){
        // draw the object or anything else...
    }
 }

re-using:

 for(i=0;i<MAX_GAME_OBJECTS;i++){
    if( ! isObjAlive[i]){
        // use the setters to customize your object for the new role...
    }
 }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.