HashSet与LinkedHashSet性能测试

时间:2015-08-03 17:29:44

标签: java performance collections

here我发红HashSet has slightly better performance than LinkedHashSet。但是当试图执行示例程序时,我得到了不同的结果。

     /*
     * HashSet not order not sorted
     */
    long hsTime = System.nanoTime();
    Set<String> hs = new HashSet<String>();
      // add elements to the hash set
    hs.add("B");
    hs.add("A");
    hs.add("D");
    hs.add("E");
    hs.add("C");
    hs.add("F");
    System.out.println("HashSet ---->"+hs); // HashSet ---->[D, E, F, A, B, C]
    System.out.println("Execution time HashSet ---->"+(System.nanoTime() - hsTime)); // Execution time HashSet ---->275764

    /*
     * LinkedHashSet will maintain its insertion order but no sorting
     */
    long lhsTime  = System.nanoTime();
    Set<String> lhs = new LinkedHashSet<String>();
      // add elements to the hash set
    lhs.add("B");
    lhs.add("A");
    lhs.add("D");
    lhs.add("E");
    lhs.add("C");
    lhs.add("F");
    System.out.println("LinkedHashSet ---->"+lhs); //LinkedHashSet ---->[B, A, D, E, C, F]
    System.out.println("Execution time LinkedHashESet ---->"+(System.nanoTime() - lhsTime)); // Execution time LinkedHashESet ---->201181

显示LinkedHashSet具有更好的效果。有人可以澄清哪一个有更好的表现。

注意:当我注释掉这两行时:

System.out.println("HashSet ---->"+hs);
System.out.println("LinkedHashSet ---->"+lhs);

它显示HashSet具有更好的表现。输出在哪里

Execution time HashSet ---->32304
Execution time LinkedHashESet ---->74414

1 个答案:

答案 0 :(得分:1)

我怀疑这是由于JVM在以下语句中输出HashSet时执行第一个循环所花费的预热时间:

System.out.println("HashSet ---->"+hs);

等同于

Iterator<E> i = iterator();
if (! i.hasNext())
    return "[]";

StringBuilder sb = new StringBuilder();
sb.append('[');
for (;;) {
    E e = i.next();
    sb.append(e == this ? "(this Collection)" : e);
    if (! i.hasNext())
    return sb.append(']').toString();
    sb.append(", ");
}
System.out.println("HashSet ---->" + sb.toString());