Daniel Sjöblom said:
This is not strictly true, but it may be that I'm misinterpreting what
you are saying.
You're giving an example of concatenating strings that are too large for
the buffers to fit into memory. The post I was replying to talked about
too many of these StringBuffer objects being created, not their being
too large to fit in memory. The two are quite different. It's
impossible to accumulate too many StringBuffer objects from string
concatenation operators and so cause an OutOfMemoryException.
Your scenario, on the other hand, could possibly avoid an
OutOfMemoryError but not in a very interesting way. Notice that you
basically just got lucky in your "smarterConcat" method. If that last
concatenation had required that the StringBuffer increase its buffer
size, it would have also ran out of memory. In real life, you might
decrease the probability of your code failing, but you'll never make it
correct.
If you know the final size of the result in advance, though, then you
could have really done some good with your smarterConcat and an explicit
StringBuffer. That code would look like this:
public static String reallySmarterConcat(String str, int iterations)
{
String str2 = new String(new char[100000]);
int resultLen = str.length() + str2.length * iterations;
StringBuffer sb = new StringBuffer(resultLen);
sb.append(str);
for (int i = 0; i < iterations; i++) sb.append(str2);
return sb.toString();
}
Also note that use of a StringBuffer in this situation (concatenation is
a loop of non-trivial size) is always good practice, but that's
primarily because it avoids the work of consistently copying the
character data, *not* because of any probable decrease in the high water
mark for memory usage of the algorithm.
--
www.designacourse.com
The Easiest Way To Train Anyone... Anywhere.
Chris Smith - Lead Software Developer/Technical Trainer
MindIQ Corporation