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
In general, most Computers have a single instruction to compare integers, longs etc and will take at most a couple of instruction cycles. Strings are normally compared by a utility function/method (there may be the odd exception to this rule).
in Java for example a String is basically represented as
/** The value is used for character storage. */
private final char value[];
/** The offset is the first index of the storage that is used. */
private final int offset;
/** The count is the number of characters in the String. */
private final int count;
And the equals method is
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;
The equals Method does both this == anObject and n == anotherString.count, both essentially integer compares, even before it starts comparing characters. It is going take a lot longer than a single instruction that a integer compare takes
The C string compare is simpler / faster than the Java equivalent but it will contain some sort of loop and multiple instructions for each pass through the loop.
This will take longer than the one instruction that a Integer Compare requires