Is number comparison faster than string comparison?

前端 未结 5 1782
没有蜡笔的小新
没有蜡笔的小新 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:15

    Comparing two numbers is magnitudes faster than comparing two strings (representing the same numbers). Comparing two numbers simply require comparing individual bits and could be done super fast using any of AND, XOR, 2's complements, etc.

    Comparing two strings is very slow and expensive. Most algorithms require iterating through entire string and matching each character.

    For example let's say we want to compare 9 with 12 (false). For numeric comparison, let's assume the algorithm compares individual bit. 9 = 1001 12 = 1100

    Here, the worst case algorithm will compare 4 bits.

    Now if we represent "9" and "12" as strings, they will be stored in memory as 16 bits each (Recall: Java uses UTF-16 to represent strings in memory) and have to be passed to a String comparison algorithm. In fact, Java's actual String comparison function is below:

    public boolean equals(Object anObject) {
        if (this == anObject) {
            return true;
        }
        if (anObject instanceof String) {
            String anotherString = (String)anObject;
            int n = count;
            if (n == anotherString.count) {
                char v1[] = value;
                char v2[] = anotherString.value;
                int i = offset;
                int j = anotherString.offset;
                while (n-- != 0) {
                    if (v1[i++] != v2[j++])
                        return false;
                }
                return true;
            }
        }
        return false;
    }
    

    As you can see, there's a lot more going around for String comparison.

提交回复
热议问题