I came across a strange performance issue related to the method StringBuilder append. I noticed that, apparently, it was a stupid mistake - string concatenation when using the constructor StringBuilder(this even appears as a warning in NetBeans IDE).
Version 1
int hash = -1;
int blockID = ...
int threadID = ...
boolean hashed = false;
@Override
public int hashCode(){
if(!hashed){
StringBuilder s = new StringBuilder(blockID+":"+threadID);
hash = s.toString().hashCode();
hashed= true;
}
return hash;
}
Millions of these objects are created at runtime, so I thought, making the following change: this will provide acceleration:
Version 2
@Override
public int hashCode(){
if(!hashed){
StringBuilder s = new StringBuilder(blockID);
s.append(":");
s.append(threadID);
hash = s.toString().hashCode();
hashed = true;
}
return hash;
}
WRONG! It turns out that version 2 is literally 100 times slower than version 1. Why ???
Additional Information
I am compiling against Java 6 (client requirement) and I am using Oracle JVM.
HashMap. , , 1, 50 , , 2.