[英]Lazy constructed ArrayList with default emptyList for better performance
Does this increase the performance if the list stay empty its life cycle? 如果列表没有生命周期,这是否会提高性能?
public class LazyArrayList<E> implements List<E> {
private List<E> list = Collections.emptyList();
public add(E e) {
if (list == Collections.EMPTY_LIST) {
list = new ArrayList();
}
list.add(e);
}
// other necessary methods
}
For example: 例如:
List<Integer> deleteList = new LazyArrayList<Integer>();
for ( MyObj o : otherList ) {
if (o.isOutdated()) {
deleteList.add(o.getId());
}
}
return deleteList;
No. ArrayList already has this optimization (in recent versions of the JRE). 否。ArrayList已经进行了优化(在JRE的最新版本中)。 It instantiates its internal array only when needed:
它仅在需要时实例化其内部数组:
/**
* Shared empty array instance used for empty instances.
*/
private static final Object[] EMPTY_ELEMENTDATA = {};
public ArrayList() {
super();
this.elementData = EMPTY_ELEMENTDATA;
}
Try with ArrayList.trimToSize() that says: 尝试使用ArrayList.trimToSize() :
Trims the capacity of this ArrayList instance to be the list's current size.
将此ArrayList实例的容量调整为列表的当前大小。 An application can use this operation to minimize the storage of an ArrayList instance.
应用程序可以使用此操作来最小化ArrayList实例的存储。
Look at ArrayList.ensureCapacity() that says: 看一下ArrayList.ensureCapacity() :
Increases the capacity of this ArrayList instance, if necessary, to ensure that it can hold at least the number of elements specified by the minimum capacity argument.
如有必要,增加此ArrayList实例的容量,以确保它至少可以容纳最小容量参数指定的元素数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.