Strings in Switch
Ulf Zibis
Ulf.Zibis at gmx.de
Tue Dec 22 05:47:07 PST 2009
For more details see my bug report:
6912520 - String#equals(Object) should benefit from hash code
<http://bugs.sun.com/bugdatabase/view_bug.do?bug_id=6912520>
-Ulf
Am 09.12.2009 20:17, Ulf Zibis schrieb:
>
> 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