• 请不要在回答技术问题时复制粘贴 AI 生成的内容
rizon
V2EX  ›  程序员

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

  •  
  •   rizon ·
    othorizon · Feb 14, 2019 · 2577 views
    This topic created in 2648 days ago, the information mentioned may be changed or developed.

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

    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 replies    2019-02-14 17:05:14 +08:00
    kosmosr
        1
    kosmosr  
       Feb 14, 2019
    ArrayList 的更快 arraycopy 基于内存的赋值
    kosmosr
        2
    kosmosr  
       Feb 14, 2019
    复制
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   3904 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 31ms · UTC 00:10 · PVG 08:10 · LAX 17:10 · JFK 20:10
    ♥ Do have faith in what you're doing.