At the Colorado Software Summit, it was mentioned to use StringBuffers to concatenate strings instead of simply using the String class (I understand that Strings are first converted to String buffers anyway when concatenation occurs). At what point does it start paying off to do this? Concatenating 2 strings? 3 strings? 4 strings? etc... Also, if you have a long string that uses concatenation (simply to improve the readability of the code), will the compiler "optimize" it for you, or should you still use String buffers. For example: String query = "select first, last, address, telephone, email" + " from employee" + " where country = 'US'" + " order by last, first"; Note: None of the strings parts are dynamic, all of them are static. David Lu
Joined: Oct 26, 2000
This is the single most wide spread performance tip around. If you check the tips page on my site, you'll find umpteen references to using StringBuffer instead of +. And I also cover this in my book. The upshot is that string concatenation of static strings that can be fully resolved and concatenated at compile-time is the most efficient form of string concatenation. The compiler concatenates the fully resolved string, and inserts a reference to just the one string. At runtime, no concatenation takes place at all. So for the example you gave, you should keep the '+' operators for readability and let the compiler manage the concatenation. Where the compiler cannot fully resolve the concatenation, as in <pre> String newString = "hi " + stringArgument + "!"; </pre> Then you may as well almost always use a StringBuffer. Two strings concatenated at runtime creates a third string (three objects total), while two strings appended to a StringBuffer requires a further String to be created if that is the complete concatenation (four objects). For concatenating more than two strings at runtime, you almost always come out ahead using a StringBuffer.