Why is StringBuilder
much faster than string concatenation using the +
operator? Even though that the +
operator internally is implemented using either StringBuffer
or StringBuilder
.
public void shortConcatenation(){
long startTime = System.currentTimeMillis();
while (System.currentTimeMillis() - startTime <= 1000){
character += "Y";
}
System.out.println("short: " + character.length());
}
//// using String builder
public void shortConcatenation2(){
long startTime = System.currentTimeMillis();
StringBuilder sb = new StringBuilder();
while (System.currentTimeMillis() - startTime <= 1000){
sb.append("Y");
}
System.out.println("string builder short: " + sb.length());
}
I know that there are a lot of similar questions posted here, but these don't really answer my question.
StringBuilder
is much faster than string concatenation using the+
operator? – Ashcraft10ms
vs100ms
and concluded that the first must be faster, although it was actually a lot slower in practice. You have to use a framework like JMH to get useable results. – Wifeless