Wednesday, February 18, 2009

String concatenation in Java with +

In Java if you System.out.println(“String 1” + “String2”) then there are no issues. The compiler will optimize it and there is no performance penalty. But if you do a String one = “String1”; String two = “String2”; System.out.println(one + two), then the compiler does not optimize this and there IS a performance issue. In these cases use String.format(“%s %s”, one, two).

 

For static Strings + concatenation is fine, for dynamic Strings, use String.format().

No comments: