Which is faster to find an item in a hashtable or in a sorted list?

后端 未结 7 2088
栀梦
栀梦 2020-12-24 06:41

Which is faster to find an item in a hashtable or in a sorted list?

7条回答
  •  Happy的楠姐
    2020-12-24 07:24

    It depends entirely on the amount of data you have stored.

    Assuming you have enough memory to throw at it (so the hash table is big enough), the hash table will locate the target data in a fixed amount of time, but the need to calculate the hash will add some (also fixed) overhead.

    Searching a sorted list won't have that hashing overhead, but the time required to do the work of actually locating the target data will increase as the list grows.

    So, in general, a sorted list will generally be faster for small data sets. (For extremely small data sets which are frequently changed and/or infrequently searched, an unsorted list may be even faster, since it avoids the overhead of doing the sort.) As the data set becomes large, the growth of the list's search time overshadows the fixed overhead of hashing, and the hash table becomes faster.

    Where that breakpoint is will vary depending on your specific hash table and sorted-list-search implementations. Run tests and benchmark performance on a number of typically-sized data sets to see which will actually perform better in your particular case. (Or, if the code already runs "fast enough", don't. Just use whichever you're more comfortable with and don't worry about optimizing something which doesn't need to be optimized.)

提交回复
热议问题