在 Java arrayList 中,同一类 TGrid
有两个不同的列表。一个有大约 1000 个元素,另一个有 10 个元素。
现在,在我的功能中,我必须根据 if/else 条件重置一些元素
在这里,我有两个选项可以执行相同的操作但是我需要知道哪个选项的性能更好。
类别:
public class TGrid{
private String pType;
private boolean one ;
private boolean one6;
private boolean one7;
private boolean three2;
getter --- setter
}
现在功能,重置对象
选项 1:
tGridList.get(count).setPType("");
tGridList.get(count).setOne(false);
tGridList.get(count).setOne6(false);
tGridList.get(count).setOne7(false);
tGridList.get(count).setThree2(false);
选项 2:
tGridList.set(count, new TGrid());
问题:哪个选项可以提供更好的性能?
最佳答案
随着时间的推移,第一个选项可能会更快。你应该将其重写为
TGrid t = tGridList.get(count);
t.setPType("");
t.setOne(false);
t.setOne6(false);
t.setOne7(false);
t.setThree2(false);
甚至在 TGrid 中引入一个clear()方法。
与第二个选项相比,这不会遇到阻塞问题。第二个中的 new-call 可以在内存压力下停止整个虚拟机。
这样做的坏处是您更改了实例,这意味着您必须关心同步。其中“关心”包括主动忽略它;)
关于java - 更好的数组列表性能选项来重置对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26418087/