Is number comparison faster than string comparison?

前端 未结 5 1843
没有蜡笔的小新
没有蜡笔的小新 2021-02-04 02:36

I heard that hashing (ie converting a string or object to a number) is used for strings and such because it is easier to compare numbers than strings. If true, what is the reaso

5条回答
  •  轮回少年
    2021-02-04 03:32

    This is not necessarily the case, but probably the case most of the time.

    Consider the following situation:

    I want to compare the string "apples" vs. "oranges". If I only want to determine "apples" == "oranges", I need only compare the first character of each string: 'a' != 'o' => "apples" != "oranges". If I hash the string and then do the comparison, it is significantly slower as I have to parse both strings and feed them into a hashing algorithm before comparing the resultant integers.

    If, however, I need to do this comparison many times, and perhaps I'm comparing "oranges" to "orangutans" a lot, then if I hash all the strings once and do the comparisons of integers many times, it will work out faster. This is the principle that a hash map is based on.

    Note, however, that hashing a string is useful for direct equals comparisons, it cannot determine if strings are lexigraphically greater or less than each other, and so ordering strings is not possible via the hashing method. (This is why HashMap in Java is unordered).

提交回复
热议问题