首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >HashSet与LinkedHashSet性能测试

HashSet与LinkedHashSet性能测试
EN

Stack Overflow用户
提问于 2015-08-03 17:29:44
回答 1查看 1.4K关注 0票数 1

这里我红了那个HashSet has slightly better performance than LinkedHashSet。但是当尝试执行一个示例程序时,我得到了一个不同的结果。

代码语言:javascript
复制
     /*
     * 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具有更好的性能。谁能澄清哪一个有更好的表现。

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

代码语言:javascript
复制
System.out.println("HashSet ---->"+hs);
System.out.println("LinkedHashSet ---->"+lhs);

这表明HashSet具有更好的性能。输出的位置

代码语言:javascript
复制
Execution time HashSet ---->32304
Execution time LinkedHashESet ---->74414
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-03 17:33:14

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

代码语言:javascript
复制
System.out.println("HashSet ---->"+hs);

这相当于类似于

代码语言:javascript
复制
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());
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31793284

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档