Performance Tip: Use StringBuilder instead of String for a non constant field.

Overview

Appending to a String is much slower than appending to a StringBuilder.

Append to a StringBuilder

From Logger.entering()
String msg = "ENTRY";
// later
for (int i = 0; i < params.length; i++) {
    msg = msg + " {" + i + "}"; 
}
Inside the loop it creates a StringBuilder and another String every time. It can be replaced with code which creates one StringBuilder and String, total.
StringBuilder msgSB = new StringBuilder("ENTRY");
// later
for (int i = 0; i < params.length; i++) {
    msgSB.append(" {").append(i).append("}"); 
}
String msg = msgSB.toString();

Comments

Popular posts from this blog

Java is Very Fast, If You Don’t Create Many Objects

Low Latency Microservices, A Retrospective

Unusual Java: StackTrace Extends Throwable