Which one is faster? List.contains() or Map.containsKey()

后端 未结 4 1439
星月不相逢
星月不相逢 2021-01-31 17:34

I\'m writing an algorithm where I look for pairs of values which when added together results in another value I\'m looking for.

I figured out that using a Map

4条回答
  •  陌清茗
    陌清茗 (楼主)
    2021-01-31 18:36

    Mapand List are interfaces, so there is no information on their implementation nor their performance. But if you use the most current implementations (LinkedList or ArrayList for List, and HashMap for Map), the contains() method must, in the worst case, go through the entire list, and compare your element with each entry. It is an O(n) operation.

    If you use an HashMap, the implementation is radically different : the HashMap contains an array with more entries than elements in it (in practice, you have an array size of between 4n/3 an 3n/2 for n elements in the map). It computes the hash of the key, which is an int, and wrap it between 0 and your array size (let's say this number is i). Then it will put the element at the index i of the array (or i+1, i+2… if previous indexes are already taken). So, when you check for the key presence with containsKey, it will re-compute the hash and the i value, and check the i, i+1… indexes until it finds an empty array cell. Theorically, you can have an O(n) worst-case, if the array is almost full, are all the keys have almost identicals i values, but with a good hash function, you have constant-time contains and get functions. (However, adding elements is fast if you don't need to resize the array, which is REALLY slow - I think you need to recompute the indexes of each key).

    So a map is really faster if you need to check the key appearance in a collection, and do not need to keep the order (there is a SortedHashMap for that, but I don't know it's performance), but it will take more memory.

    Also, if you don't need the key-value thing, you can use a HashSet (which is internally the same as an HashMap).

提交回复
热议问题