Is the JVM a fix for my inefficient code by keeping the results of similar method calls within the same method?

Given the code

if (linkedHashMap.get(string) == null) { 
  linkedHashMap.put(string, object);
} else { 
  linkedHashMap.get(string).increment();
}

      

Does the Interputer / JVM linkedHashMap.get(string)

use that: is used twice and hence assigns a variable for this call. Or is it just making the same call twice ineffectively?

+3


source to share


2 answers


Given a fairly advanced JIT and a fairly trivial implementation get()

- and the equals()

one called by it - it might be optimized at some point. But there are no guarantees.

Implementation details get()

are important because they can either involve memory visibility effects (atoms, locks) or have complexity that exceeds the compiler's ability to perform redundant elimination of code.



eg. I would assume that the map generated Collections.singletonMap

is simple enough to optimize. But ConcurrentHashMap

, of course, not related to its use of volatile and castles.

But in the end, the only way to be sure is to look at the generated assembly for the method in question, after it's hot enough for its calls to be considered JITed.

+2


source


There is no such thing as an intercomponent. The just-in-time compiler can recognize duplication, but only if the methods being called are simple enough to be inlined, which is probably not the case for HashMap.get. However, the redundant lookup takes less than a microsecond, so if the code is not executed millions of times per second, the performance impact will not be significant.

A simple way to avoid redundant search (which works well with ConcurrentMaps too) would be



linkedHashMap.merge(string, 1, Integer::sum);

      

0


source







All Articles