0

I want to know the working time of some methods in my study project by Java tools. When I tried to use System.nanoTime(), I had noticed, that comparison of the working time of two methods looks a litle bit strange. The first and the second methods should work for the same time, but I got another result in console - the working time distinguished in several times.

Whether calculating time by System.nanoTime() function gives different efficiency results on the simple code:

String a = "a";
String b = "b";
String c = "c";
String d = "d";

HashMap<String, String> stringMap = new HashMap<>();
stringMap.put(a, "map_a");
stringMap.put(b, "map_b");

HashMap<String, String> secondStringMap = new HashMap<>();
secondStringMap.put(c, "map_c");
secondStringMap.put(d, "map_d");

String[] firstArray = new String[2];
String[] secondArray = new String[2];

long startTime = System.nanoTime();

firstArray[0] = stringMap.get(a);
secondArray[1] = stringMap.get(b);

long midTime = System.nanoTime();

firstArray[0] = secondStringMap.get(c);
secondArray[1] = secondStringMap.get(d);

long endTime = System.nanoTime();

System.out.println(midTime - startTime);
System.out.println(endTime - midTime);

And I got a very interesting result - the first part worked for approximately 5-10 times slower than the second.

So the question is:

Why does calculating working time with System.nanoTime() give different result for the first and the second part of the code? Is there any better way to count time?

richi_urb
  • 9
  • 1
  • 2
    The Java runtime is complex. The just-in-time compiler may have decided to compile HashMap into native code by the time the second pair of `get` calls occurred. Single runs are rarely a good way to perform benchmarking in Java. – VGR Dec 17 '21 at 01:44
  • [*Java Microbenchmark Harness (JMH)*](https://github.com/openjdk/jmh#java-microbenchmark-harness-jmh) – Basil Bourque Dec 17 '21 at 01:47

0 Answers0