V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
rizon
V2EX  ›  程序员

CollectionUtils.addAll 和 ArrayList.addAll 哪个性能好

  •  
  •   rizon ·
    othorizon · 2019-02-14 17:00:35 +08:00 · 2154 次点击
    这是一个创建于 1897 天前的主题,其中的信息可能已经有所发展或是发生改变。

    求问 这两种方式哪个效率高?性能好

    List<T> colParams = new ArrayList<>();
    //方式 1
    CollectionUtils.addAll(colParams,
    	colParam.getParams().stream()
    	.map(p -> p).iterator());
    
    //方式 2
    colParams.addAll(colParam.getParams().stream()
    	.map(p -> p).collect(Collectors.toList()));
     
    

    这是 CollectionUtils.addAll 的源码

        public static <C> boolean addAll(final Collection<C> collection, final Iterator<? extends C> iterator) {
            boolean changed = false;
            while (iterator.hasNext()) {
                changed |= collection.add(iterator.next());
            }
            return changed;
        }
    

    这是 ArrayList.addAll 的源码

        public boolean addAll(Collection<? extends E> c) {
            Object[] a = c.toArray();
            int numNew = a.length;
            ensureCapacityInternal(size + numNew);  // Increments modCount
            System.arraycopy(a, 0, elementData, size, numNew);
            size += numNew;
            return numNew != 0;
        }
    

    另外一个问题,stream 中的.iterator().collect(Collectors.toList())) 这两个区别大吗?


    还有个问题,foreach 和 for 循环区别大吗?

    2 条回复    2019-02-14 17:05:14 +08:00
    kosmosr
        1
    kosmosr  
       2019-02-14 17:05:04 +08:00
    ArrayList 的更快 arraycopy 基于内存的赋值
    kosmosr
        2
    kosmosr  
       2019-02-14 17:05:14 +08:00
    复制
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   3171 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 28ms · UTC 14:33 · PVG 22:33 · LAX 07:33 · JFK 10:33
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.