Why is this using concatenation in the StringBuilder 100X constructor faster than calling append ()?

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;     //lazily computed, also present in Version 2
int blockID = ...  //0 to 1000, also present in Version 2
int threadID = ... //0 to 1000, also present in Version 2
boolean hashed = false;       //also present in Version 2

@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.

+4
2

, .

public int hashCode(){
    if(!hashed){
        StringBuilder s = new StringBuilder(
                  new StringBuilder(blockID).append(":").append(threadID).toString());
        hash = s.toString().hashCode();
        hashed= true;
    }

    return hash;
}

, , .

, , , , .

+1

StringBuilder blockID . . .

public StringBuilder (int capacity)

, .

:

StringBuilder s = new StringBuilder(9);
s.append(blockID).append(':').append(threadID);
+14

All Articles