zoukankan      html  css  js  c++  java
  • Collections.addAll 为什么比collection.addall 快(转)

    from: http://stackoverflow.com/a/3343829/5032462

    在stackoverflow上看到的一篇回答,老外真是太professional了,mark一下。最后的summary值得看一下。

    The Java API docs say the following about Collections.addAll

    The behavior of this convenience method is identical to that of c.addAll(Arrays.asList(elements)), but this method is likely to run significantly faster under most implementations.

    So if I understand correctly, a) is slower than b):

    a)

     Collection<Integer> col = new ArrayList<Integer>();
     col.addAll(Arrays.asList(1, 2, 3, 4, 5));

    b)

    Collection<Integer> col = new ArrayList<Integer>();
    // Collections.addAll(col, Arrays.asList(1, 2, 3, 4, 5)); <-- won't compile
    Collections.addAll(col, 1, 2, 3, 4, 5);

    Let's take a closer look at the two of them:

    // a)
    col.addAll(Arrays.asList(1, 2, 3, 4, 5));

    Here's what happens:

    1. varags + autoboxing creates Integer[]
    2. Arrays.asList creates a List<Integer> backed by the array
    3. addAll iterates over a Collection<Integer> using Iterator<Integer>
    // b)
    Collections.addAll(col, 1, 2, 3, 4, 5);

    Here's what happens:

    1. varargs + autoboxing creates Integer[]
    2. addAll iterates over an array (instead of an Iterable<Integer>)

    We can see now that b) may be faster because:

    • Arrays.asList call is skipped, i.e. no intermediary List is created.
    • Since the elements are given in an array (thanks to varargs mechanism), iterating over them may be faster than using Iterator.

    That said, unless profiling shows otherwise, the difference isn't likely to be "significant". Do not optimize prematurely. While Java Collection Framework classes may be slower than arrays, they perform more than adequately for most applications.

    API links

    See also

    Related questions


    Summary

    • If you're adding elements from an array, you can use Collections.addAll(col, arr)
      • Remember that varargs are also done using arrays
    • If you're adding elements from a Collection, use col.addAll(otherCol)
      • Do NOT e.g. Collections.addAll(col, otherCol.toArray())
        • Such roundabout way is likely to be slower!
    • It's not that one is supremely faster than the other
      • It's about skipping unnecessary steps given the current situation
  • 相关阅读:
    一些经验
    倍增(在线)求LCA
    IDA*算法——骑士精神
    A*算法——第K短路
    (持续更新)一些黑科技和技巧
    逆元
    方便人类——信息学训练专用库
    PHP单点登陆
    PHP 中运用 elasticsearch
    PHP斐波那契数列
  • 原文地址:https://www.cnblogs.com/BJUT-2010/p/5577977.html
Copyright © 2011-2022 走看看