I am creating a game for android. And i have noticed that whenever the garbage collector kicks in, the game experiences a large amount of lag.
When the App is first run, all of the objects are created and added into arrayLists as follows:
br1 = ImgLoader.getResizedBitmap(BitmapFactory.decodeResource(
context.getResources(), R.drawable.branchfl, MainActivity.opt),
MainActivity.height / 12, MainActivity.width / 6);
for (int i = 0; i < 10; ++i) {
branches_available.add(new Sprite("Branch", br1, 0, 0));
}
The Sprite object consists of a Bitmap, and several methods that allow me to modify said Bitmap. So in the above code, im storing 10 Sprites into an ArrayList. Now later in the code, i need to generate said sprites into my level dynamically. So all i do is this:
if (rand == 1) {
branches_available.get(0).image = bToAdd;
branches_available.get(0).xPos = (screenWidth - treeWid - bToAdd
.getWidth()) + bToAdd.getWidth() / 18;
branches_available.get(0).yPos = 0 - bToAdd.getHeight();
branches_available.get(0).height = bToAdd.getHeight();
branches_available.get(0).width = bToAdd.getWidth();
branches.add(branches_available.get(0));
branches_available.remove(0);
This takes the object from the first array and adds it to the second array. And in the draw method, only the second arrayList is drawn. Now when the objects leave the screen, i do the following:
branchesSize = branches.size();
for (int i = 0; i < branchesSize; ++i) {
branches.get(i).move(0, speed);
if (branches.get(i).yPos > screenHeight) {
branches_available.add(branches.get(i));
branches.remove(i);
i--;
branchesSize -= 1;
// System.gc(); // Force Garbage Collection
}
}
So they are added back into the available array so they can be reused again in the above method if need be.
Despite doing this, i am still getting a large amount of lag in my application. Could it be because im removing the object from the array?
What am i doing wrong?
Thank you!