如果列表没有生命周期,这是否会提高性能?

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
}


例如:

List<Integer> deleteList = new LazyArrayList<Integer>();
for ( MyObj o : otherList ) {
    if (o.isOutdated()) {
        deleteList.add(o.getId());
    }
}
return deleteList;

最佳答案

否。ArrayList已经进行了优化(在JRE的最新版本中)。它仅在需要时实例化其内部数组:

/**
 * Shared empty array instance used for empty instances.
 */
private static final Object[] EMPTY_ELEMENTDATA = {};

public ArrayList() {
    super();
    this.elementData = EMPTY_ELEMENTDATA;
}

关于java - 延迟构造的ArrayList和默认的emptyList以获得更好的性能,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23118791/

10-13 06:42