简体   繁体   English

延迟构造的ArrayList和默认的emptyList以获得更好的性能

[英]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.

相关问题 使用JIT编译器的Collections.emptyList和空ArrayList的性能 - Performance of Collections.emptyList and empty ArrayList with JIT compiler 为什么ArrayList不会覆盖equals()以获得更好的性能? - Why does not ArrayList override equals() for better performance? 更好的arraylist性能选项可以重置对象 - Better arraylist performance option to reset object 我们可以用 ArrayDeque 替换 ArrayList 以获得更好的性能吗? - Can We replace ArrayList with ArrayDeque for better performance? 在使用 Collections.emptyList() 声明后,懒惰地将列表重新初始化为可修改 - Lazy reinit a list to modifiable after declaring with Collections.emptyList() 性能更好,SQLite查询与ArrayList <Object> 在记忆中 - Better Performance, SQLite queries vs ArrayList<Object> in memory 从性能的角度来看,哪个更好..arraylist 或数组? - which one is better from performance point of view..arraylist or array? ArrayList的性能 - Performance of ArrayList 自动将构造的每个Class对象添加到ArrayList中 - Automatically adding every Class object constructed into an ArrayList 当使用 ArrayList 的 Stack 或 Queue 实现比在 Java 中实现的 LinkedList 提供更好、更快的性能时,是否有任何情况? - Is there any case when a Stack or a Queue implementation with ArrayList gives better, faster performance then a LinkedList implemented in Java?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM