Strings in Switch
Ulf Zibis
Ulf.Zibis at gmx.de
Wed Dec 9 11:17:01 PST 2009
Am 09.12.2009 16:34, Fredrik Öhrström schrieb:
> .... to optimize
> this sequence of compares and it avoids forcing a full calculation of a
> hash code that has to traverse the full string. Remember that a string
> compare can terminate early, a hashcode calculation cannot. Also a
> string compare works on as large blocks as possible per iteration
> (8bytes in 64 bit machines, even 16byte blocks with SSE2).
Good point. If a compare on a string is rarely, and especially if it's
total length is not trivial, the hash code computation should be more
expensive, but after some repeated compairs on the same string, the
hashcode algorithm would win.
Here an enhanced String#equals() implementation, which values the length
of every invoked compare on characters:
int equalByHashThreshold = count;
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 &&
(equalByHashThreshold > 0 ||
hash() == anotherString.hash())) {
char v1[] = value;
char v2[] = anotherString.value;
int i = offset;
int j = anotherString.offset;
while (n-- != 0)
if (v1[i++] != v2[j++]) {
if (equalByHashThreshold > 0)
equalByHashThreshold -= (count - n);
return false;
}
return true;
}
}
return false;
}
public int hashCode() {
int h = hash;
if (h == 0) {
int off = offset;
char val[] = value;
int len = count;
for (int i = 0; i < len; i++) {
h = 31*h + val[off++];
}
hash = h;
equalByHashThreshold = 0;
}
return h;
}
-Ulf
More information about the coin-dev
mailing list