Hashmap vs Array performance

HashMap uses an array underneath so it can never be faster than using an array correctly.

Random.nextInt() is many times slower than what you are testing, even using array to test an array is going to bias your results.

The reason your array benchmark is so slow is due to the equals comparisons, not the array access itself.

HashTable is usually much slower than HashMap because it does much the same thing but is also synchronized.

A common problem with micro-benchmarks is the JIT which is very good at removing code which doesn’t do anything. If you are not careful you will only be testing whether you have confused the JIT enough that it cannot workout your code doesn’t do anything.

This is one of the reason you can write micro-benchmarks which out perform C++ systems. This is because Java is a simpler language and easier to reason about and thus detect code which does nothing useful. This can lead to tests which show that Java does “nothing useful” much faster than C++ 😉

Leave a Comment