list.clear() vs list = new ArrayList<Integer>(); [英] list.clear() vs list = new ArrayList<Integer>();
问题描述
这 2 个选项中哪个更好更快地清除 ArrayList,为什么?
Which one of the 2 options is better and faster to clear an ArrayList, and why?
list.clear()
或
list = new ArrayList<Integer>();
碰巧我必须在随机时间清除我的 ArrayList 中的所有条目,我无法知道将来会有多少新条目,可能是 0 或 1000.哪种方法更快更好,为什么?
It happens that I have to, at random times, clear all entries from my ArrayList and I have no way to know how many new entries there will be in the future, there might be 0 or a 1000. Which method is faster and better, and why?
推荐答案
如果没有基准测试很难知道,但是如果您的 ArrayList 中有很多项并且平均大小较小,那么制作一个新的可能会更快数组列表.
It's hard to know without a benchmark, but if you have lots of items in your ArrayList and the average size is lower, it might be faster to make a new ArrayList.
http://www.docjar.com/html/api/java/util/ArrayList.java.html
public void clear() {
modCount++;
// Let gc do its work
for (int i = 0; i < size; i++)
elementData[i] = null;
size = 0;
}
这篇关于list.clear() vs list = new ArrayList<Integer>();的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!