我有发动机的方法我使用(andengine):字符串和垃圾收集
public final void setText(String pString){...}
我的应用程序更新每1秒从静止INT
mScoreText.setText(""+PlayerSystem.mScore);
问题得分是这每隔一秒创建一个新的String对象,并在1分钟后,我有59个字符串对象通过GC和其他AbstractStringBuilders和init收集...
我找到了andeng的部分解决方案INE论坛这样的:
private static StringBuilder mScoreValue = new StringBuilder("000000");
private static final char[] DIGITS = {'0','1','2','3','4','5','6','7','8','9'};
mScoreValue.setCharAt(0, DIGITS[(PlayerSystem.mScore% 1000000)/100000]);
mScoreValue.setCharAt(1, DIGITS[(PlayerSystem.mScore% 100000)/10000]);
mScoreValue.setCharAt(2, DIGITS[(PlayerSystem.mScore% 10000)/1000]);
mScoreValue.setCharAt(3, DIGITS[(PlayerSystem.mScore% 1000)/100]);
mScoreValue.setCharAt(4, DIGITS[(PlayerSystem.mScore% 100)/10]);
mScoreValue.setCharAt(5, DIGITS[(PlayerSystem.mScore% 10)]);
mScoreText.setText(mScoreValue.toString());
但主要问题仍然存在,的ToString()将返回新对象每次调用
有什么办法解决?
你真的关心每个*秒*一个字符串吗?这对我来说似乎并不多,特别是因为我期望每次点击或其他事件都会创建一个新的(事件)对象。 –
是的。停止关心。垃圾收集器足够快,以至于每秒一次分配的担心完全是惊人的,不成比例。这种毫无意义的小提琴工作就是计算机最擅长的 - 让他们这样做,并利用你的智力来获得更有价值的东西。 –
使用该代码将是严重的过早优化的情况。我认为最后所有的模操作,分区,从数组中提取数据和设置字符都会比一次创建字符串和相关的垃圾回收花费更多的处理时间。就像其他人指出的那样,最后你用toString()创建了一个String。如果您正在处理这样的限制,即每分钟分配60个小对象太多,那么Java并不是您想要使用的语言。 C或装配将更接近该商标。 –