Which is faster, Hash lookup or Binary search?

后端 未结 17 2505
你的背包
你的背包 2020-12-02 06:47

When given a static set of objects (static in the sense that once loaded it seldom if ever changes) into which repeated concurrent lookups are needed with optimal performanc

17条回答
  •  一整个雨季
    2020-12-02 07:15

    Hashes are typically faster, although binary searches have better worst-case characteristics. A hash access is typically a calculation to get a hash value to determine which "bucket" a record will be in, and so the performance will generally depend on how evenly the records are distributed, and the method used to search the bucket. A bad hash function (leaving a few buckets with a whole lot of records) with a linear search through the buckets will result in a slow search. (On the third hand, if you're reading a disk rather than memory, the hash buckets are likely to be contiguous while the binary tree pretty much guarantees non-local access.)

    If you want generally fast, use the hash. If you really want guaranteed bounded performance, you might go with the binary tree.

提交回复
热议问题