Hash Table v/s Trees

前端 未结 4 483
醉话见心
醉话见心 2021-01-06 03:13

Are hashtables always faster than trees? Though Hashtables have O(1) search complexity but suppose if due to badly designed hash function lot of collisions happen and if we

4条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-06 03:30

    Are hashtables always faster than trees?

    No, not always. This depends on many things, such as the size of the collection, the hash function, and for some hash table implementations - also the number of delete ops.

    hash-tables are O(1) per op on average - but this is not always the case. They might be O(n) in worst cases.

    Some reasons I can think of at the moment to prefer trees:

    1. Ordering is important. [hash-tables are not maintaining order, BST is sorted by definition]
    2. Latency is an issue - and you cannot suffer the O(n) that might occur. [This might be critical for real-time systems]
    3. Ther data might be "similar" related to your hash function, and many elements hashed to the same locations [collisions] is not unprobable. [this can be sometimes solved by using a different hash function]
    4. For relatively small collections - many times the hidden constant between hashtable's O(1) is much higher then the tree's - and using a tree might be faster for small collections.

    However - if the data is huge, latency is not an issue and collisions are unprobable - hash-tables are asymptotically better then using a tree.

提交回复
热议问题