首先,我想说这是我正在开发的Android游戏的一部分。垃圾收集器大约每三秒运行一次,这会导致游戏中出现短暂(但明显)的延迟。我已将其缩小到我的代码中的一个方法(粘贴在下面)。当不使用此部件时,垃圾收集器大约每11秒运行一次,并且滞后较少。此代码是使用树结构检测与对象冲突的对象的一部分。对象topLeft,topRight,bottomLeft和bottomRight是相同类型的对象,它们会以递归方式检查碰撞。我主要想知道这里是否有任何东西会产生大量的垃圾,如果这是每帧运行的。
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);
}
}
答案 0 :(得分:1)
对topLeft.getBounding()
的调用每次都会创建一个新的Rectangle。
如果您经常致电getCollisionTiles()
,这将是很多对象。在多次调用getCollisionTiles()
之前,你可能会提取一次边界矩形。
答案 1 :(得分:0)
好吧,我想我已经解决了这个问题。 HashMaps经常在我的程序中使用,我从它们切换到SparseArray。此外,渲染切片的方式是为每个绘制的切片创建一个新的Rect,因此我优化了它以更有效地使用此方法并减少垃圾。