For immutable class String; String :: hashCode
computation will happen only once in life time of that object. So calling hashCode()
after the first time is always just returning private int hash
. No CPU will be wasted on computation.
public int hashCode() {
int h = hash;
if (h == 0 && value.length > 0) { // **h != 0 in second time**
char val[] = value;
for (int i = 0; i < value.length; i++) {
h = 31 * h + val[i];
}
hash = h;
}
return h;
}
As we know the contract between hashcode and equals as
equal objects must produce the same hash code
So i believe below piece of code will improve the performance on string equals(). This may be redundant in hashmap, since hashmap already got the bucket based on hashcode, but this has good performance improvement on BIG List search.
//Does the below will improve equals performance on BIG LIST?
if (this.hashCode() != anObject.hashCode()) {
return false;
}
Please comment your thoughts the below api.
public boolean equals(Object anObject) {
if (this == anObject) {
return true;
}
if (this.hashCode() != anObject.hashCode()) {
return false;
}
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;
}
UPDATE
As mentioned by 'dasblinkenlight' there is some cpu cycles required only at the first time of hashcode() API is called.
Since Java is maintaining String Pool; and if application requires large String multiple time comparison other than at hashing; then we can go for Utility method like below.
public boolean StringCompare (String one, String two) {
if (one == two) {
return true;
}
if (one.hashCode() != two.hashCode()) {
return false;
}
int n = one.count;
if (n == two.count) {
char v1[] = one.value;
char v2[] = two.value;
int i = one.offset;
int j = two.offset;
while (n-- != 0) {
if (v1[i++] != v2[j++])
return false;
}
return true;
}