【问题标题】:Different execution time for HashMap and HashSet based on the order of execution?HashMap 和 HashSet 基于执行顺序的不同执行时间?
【发布时间】:2013-11-22 12:16:57
【问题描述】:

如果我交换 HashMap 和 HashSet,我会得到不同的执行时间。首先出现的执行时间总是很高(HashMap/Hashset)。我不确定这背后的原因。任何帮助表示赞赏

执行 1 - 首先是 HashMap,然后是 HashSet --- 地图耗时:2071ms, 加起来耗时:794ms

执行 2 - 首先是 HashSet,然后是 HashMap --- 设置添加时间:2147ms, 加图耗时:781ms

private static Random secureRandom = new SecureRandom();

public static void main(String args[])
{

    int testnumber = 1000000;

    // HashMap
    long starttimemap = System.currentTimeMillis();
    Map<String, String> hashmap = new HashMap<String, String>();
    for (int i = 0; i < testnumber; i++)
    {
        hashmap.put(Long.toHexString(secureRandom.nextLong()), "true");
    }
    long endtimemap = System.currentTimeMillis();
    System.out.println("Time taken map add: " + (endtimemap - starttimemap) + "ms");

    // HashSet
    long starttimeset = System.currentTimeMillis();
    Set<String> hashset = new HashSet<String>();

    for (int i = 0; i < testnumber; i++)
    {
        hashset.add(Long.toHexString(secureRandom.nextLong()));
    }

    long endtimeset = System.currentTimeMillis();
    System.out.println("Time taken set add: " + (endtimeset - starttimeset) + "ms");
}

【问题讨论】:

    标签: java hashmap hashset


    【解决方案1】:

    原因在于 JVM 的工作方式。 JIT 编译器需要一些时间来启动,因为它会根据执行次数来决定要编译哪些代码。

    所以,第二遍更快是完全自然的,因为 JIT 已经将大量 Java 代码编译为本机代码。

    如果您使用 -Xint 选项(禁用 JIT)启动程序,两次运行的执行时间应该大致相等。

    【讨论】:

      【解决方案2】:

      一个可能的原因是您在执行基准测试之前没有预热 JIT。

      基本上,Java 会先执行一段时间的字节码(这有点慢),然后才弄清楚经常使用什么来证明 JIT 将其编译为本机机器码(更快)是合理的。因此,无论先发生什么,通常都会比较慢。

      在开始真正的基准测试之前多次运行这两个东西,让它有机会 JIT 相关代码。

      【讨论】:

        【解决方案3】:

        您没有得到不同的执行时间,您得到的是相同的执行时间。无论您使用HashMap 还是HashSet,第一个循环的时间相同,第二个循环的时间相同。第一个和第二个的区别已经解释过了,这是由于 JVM 的优化。使用HashMapHashSet 并不奇怪,因为HashSet 在内部使用HashMap。您一直在执行相同的代码。

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2015-08-13
          • 2018-06-16
          • 2018-08-26
          • 2011-08-19
          • 1970-01-01
          • 2019-09-07
          • 1970-01-01
          相关资源
          最近更新 更多