Your explanation why it is inefficient is accurate, in at least the languages I am familiar with (C, Java, C#), though I would disagree that it is universally common to perform massive amounts of string concatenation. In the C# code I work on, there is copious usage of StringBuilder
, String.Format
, etc. which are all memory saving techiniques to avoid over-reallocation.
So to get to the answer for your question, we must ask another question: if it's never really an issue to concatenate strings, why would classes like StringBuilder
and StringBuffer
exist? Why is the use of such classes included in even semi-beginner programming books and classes? Why would seemingly pre-mature optimization advice be so prominent?
If most string-concatenating developers were to base their answer purely on experience, most would say it never makes a difference and would shun the use of such tools in favor of the "more readable" for (int i=0; i<1000; i++) { strA += strB; }
. But they never measured it.
The real answer to this question could be found in this SO answer, which reveals that in one instance, when concatenating 50,000 strings (which depending on your application, may be a common occurence), even small ones, resulted in a 1000x performance hit.
If performance literally doesn't mean anything at all, by all means concatenate away. But I would disagree that using alternatives (StringBuilder) is difficult or less readable, and therefore would be a reasonable programming practice that shouldn't invoke the "premature optimization" defense.
UPDATE:
I think what this comes down to, is know your platform and follow its best practices, which are sadly not universal. Two examples from two different "modern languages":
- In another SO answer, the exact opposite performance characteristics (array.join vs +=) were found to be sometimes true in JavaScript. In some browsers, string concatenation appears to be optimized automatically, and in other cases it isn't. So the recommendation (at least in that SO question), is to just concatenate and not worry about it.
- In another case, a Java compiler can automatically replace concatenation with a more efficient construct such as StringBuilder. However, as others have pointed out, this is indeterministic, not guaranteed, and using StringBuilder doesn't hurt readability. In this particular case, I would tend to recommend against the use of concatenation for large collections or relying on an indeterministic Java compiler behavior. Similarly, in .NET, no optimization of the sort is performed, ever.
It's not exactly a cardinal sin to not know every nuance of every platform right away, but ignoring important platform issues like this would almost be like moving from Java to C++ and not caring about deallocating memory.