0

I decided to make an experiment. I created two hash maps in Java. One hash map with 100 entries and a second hash map with 10000000 entries.

public class MainJava {

private static int NUMBER_OF_ITERATIONS = 1000000;
private static int SMALL_MAP_SIZE = 100;
private static int BIG_MAP_SIZE = 10000000;

public static void main(String[] args) {
    Map<Integer, String> smallMap = createSmallHashMap();
    long start = System.currentTimeMillis();
    for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
        smallMap.get(i % SMALL_MAP_SIZE);
    }
    long end = System.currentTimeMillis();
    System.out.println("small: " + (end - start));

    Map<Integer, String> bigMap = createBigHashMap();
    start = System.currentTimeMillis();
    for (int i = 0; i < NUMBER_OF_ITERATIONS; i++) {
        bigMap.get(i % BIG_MAP_SIZE);
    }
    end = System.currentTimeMillis();
    System.out.println("big: " + (end - start));
}

private static Map<Integer, String> createSmallHashMap() {
    Map<Integer, String> smallMap = new HashMap<>();
    for (int i = 0; i < SMALL_MAP_SIZE; i++) {
        smallMap.put(i, "small-map" + i);
    }
    return smallMap;
}

private static Map<Integer, String> createBigHashMap() {
    Map<Integer, String> bigMap = new HashMap<>();
    for (int i = 0; i < BIG_MAP_SIZE; i++) {
        bigMap.put(i, "big-map" + i);
    }
    return bigMap;
}

}

I retrieved values from both hashmaps and measured the time it took in both cases. I ran the code several and saw that the time to retrieve values from the big hashmap was almost ALWAYS longer than the small hashmap.

How is it possible? Retrieval time complexity of a hash map is 0(1). I'd expect similar time values for both maps.

CrazySynthax
  • 13,662
  • 34
  • 99
  • 183
  • Jon Skeet, The man who rules over this website, has answered this question gracefully as seen in his answer here: https://stackoverflow.com/questions/4553624/hashmap-get-put-complexity – dxjuv Feb 21 '20 at 08:36
  • From the [docs](https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html): `This class ... does not guarantee that the order will remain constant over time. ... Iteration over collection views requires time proportional to the "capacity" of the HashMap instance (the number of buckets) plus its size (the number of key-value mappings)` – default locale Feb 21 '20 at 08:58
  • The bigger map requires a bigger number of buckets, and the performance of `get` depends on the number of buckets. – default locale Feb 21 '20 at 08:59

0 Answers0