1

First off, I would like to say that this is part of an Android game that I am working on. The garbage collector is running about every three seconds, which causes brief (but noticeable) lag in my game. I have narrowed it down to one method in my code (pasted below). When this part is not used, the garbage collector runs about every 11 seconds instead and there is less lag. This code is part of an object that uses a tree structure to detect collisions with objects. The objects topLeft, topRight, bottomLeft, and bottomRight are objects of the same type that are checked recursively for collisions. I mainly wanted to know if there was anything in here that would build up large amounts of garbage if this was run each frame.

public HashSet<Integer> getCollisionTiles(Rect r) { resetTempList(); if(topLeft!=null && topLeft.containsTiles() && Rect.intersects(r, topLeft.getBounding())) topLeft.addCollisionTiles(tempList, r); if(topRight != null && topRight.containsTiles() && Rect.intersects(r, topRight.getBounding())) topRight.addCollisionTiles(tempList, r); if(bottomLeft != null && bottomLeft.containsTiles() && Rect.intersects(r, bottomLeft.getBounding())) bottomLeft.addCollisionTiles(tempList, r); if(bottomRight != null && bottomRight.containsTiles() && Rect.intersects(r, bottomRight.getBounding())) bottomRight.addCollisionTiles(tempList, r); return tempList; } private void addCollisionTiles(HashSet<Integer> tList, Rect r) { if(level==maxLevel) { for(Integer i: keyListTiles) tList.add(i); } else { if(topLeft!=null && topLeft.containsTiles() && Rect.intersects(r, topLeft.getBounding())) topLeft.addCollisionTiles(tList, r); if(topRight != null && topRight.containsTiles() && Rect.intersects(r, topRight.getBounding())) topRight.addCollisionTiles(tList, r); if(bottomLeft != null && bottomLeft.containsTiles() && Rect.intersects(r, bottomLeft.getBounding())) bottomLeft.addCollisionTiles(tList, r); if(bottomRight != null && bottomRight.containsTiles() && Rect.intersects(r, bottomRight.getBounding())) bottomRight.addCollisionTiles(tList, r); } } 

2 Answers 2

1

The call to topLeft.getBounding() will create a new Rectangle every time.

This will be a lot of objects if you call getCollisionTiles() frequently. You could possibly extract the bounding rectangles once before calling getCollisionTiles() a bunch of times.

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

Comments

0

Alright, I think I have solved this problem. HashMaps are used often in my program, and I switched from them to SparseArray. Also, the way that tiles were rendered was creating a new Rect for each drawn tile, so I optimized that to use this method more effectively and create less garbage.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.