The soul is dyed the color of its thoughts. Think only on those things that are in line with your principles and can bear the light of day. The content of your character is your choice. Day by day, what you do is who you become. Your integrity is your destiny - it is the light that guides your way. - Heraclitus
Of course you can vary the size of NUM_TIMES - but the performance of badConcatenation() is remarkably appalling; you'll probably want to comment it out before increasing NUM_TIMES too much. The point here is that you can get a tremendous performance penalty when you concatenate to a string that's used in a loop, because each time, that string's getting bigger and bigger, and the time it takes to recopy the contents to a StringBuilder or StringBuffer and then back to a new String gets bigger and bigger. In comparison, the concatenations in goddConcatenation() aren't bad at all - the contents of the StringBuilder/Buffer are always fairly small, so recopying it is not a big deal.
Given this, many programmers (myself included) will go ahead and use + for concatenation inside a loop, for improved readability, as long as the + never includes a term that's growing bigger and bigger each iteration. If I really need to optimize performance I'll go ahead and use append() for each and every element to be appended - but most of the time, it really doesn't matter. The difference between goodConcatenation() and bestConcatenation() is minor; it's only badConcatenation() that you have to worry about.
Originally posted by Dan John: I want to use the string buffer append method and inside use the + operator for strings. Is there a big performace hit with this?
There are *so* many myths related to this issue. The truth is oh so trivial and no such generalisation of reality ever holds - ever. That is to say, the following general assertions are all false: 1. StringBuffer/StringBuilder is faster than the String concatenation operator 2. StringBuffer/StringBuilder is always at least equal in performance to the String concatenation operator 3. Using the String concatenation operator in a loop will result in lesser performance 4. The use of the String concatenation operator always compiles to the use of StringBuffer 5. The use of the String concatenation operator always compiles to the use of either StringBuffer ot StringBuilder on all known implementations
I'll leave it as a reader exercise to invalidate each of these absurd, albeit common, statements. Once this has been achieved, a more informed decision regarding the consequences of each alternative in the many different possible contexts can be made.