简体   繁体   中英

Performance of HashMap<String, Comparable> against HashMap<String, Object> - Java

All,

I am working on an existing system where the developer had defined a lot of HashMaps with following definition:

HashMap<String, Comparable> x = new HashMap<String, Comparable>();

Now, there is absolutely no need of comparison for the value part of the hashmap since it simply represents only a single piece of information. The developer used Comparable since the only expected values were String and int types(converted to Integer object) and the developer assumed the best way to store both data types is using Comparable interface.

So, I went ahead and changed the code since there was no point of comparison here by defining the HashMap as:

HashMap<String, Object> y = new HashMap<String, Object>();

I had timed the code execution for before and after change. I am a bit surprised as to why the code is taking more time to execute after my changes were deployed (though not a performance bottleneck currently).

Can anyone please help me understand the change in behavior due to my code updates?

Both are identical in terms of performance as the value is not used for hashing (only the key is).

How are you timing your code? Make sure you time each test case separately. Do not do the following as the second test will have the benefit of the first test having "warmed-up" the JVM. My guess is that your test is flawed or you're seeing normal execution time variations.

public static void main(String[] args) {
    for loop {
        test HashMap<String, Comparable>
    }

    for loop {
        test HashMap<String, Object>
    }
}

There isn't any difference. The type information is erased at runtime, so perhaps the problem lies elsewhere.

My guess is that unless you're doing something elsewhere that means performance drops (I see no reason why you should see a drop from just what you've mentioned) is that the benchmark you're using is flawed. Using currentTimeMillis() or even nanoTime() won't take into account the JIT warming up, optimising various operations more quickly than others, or anything like that - and any change in your code could affect it in that way.

My advice is to use a profiler to get a more real-world idea of how long it takes - if it's significantly longer when you use that approach, then you might start looking into problems with the code. I just fear if you're relying on trivial currentTimeMillis() calls you may well end up trying to track down performance issues that don't actually exist (at least not where you think they do.)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM