The Ideal solution will be using a StringBuffer to concatenate those string and return , because by concatenating String we end up in creating lot of new objects ,since string are immutable . Hope this helps

"ideal" was probably not the best choice of words by me. One thing you'll learn is that there is never and ideal solution that applies to all possible scenarios. Every solution has tradeoffs that have to be weighed and balanced. For example, there are some situations where a bubble sort, which can be horribly slow, is actually the best solution, where a quick-sort, which is usually quite fast, would be a wretched choice.

So, without know the specifics of what you want to do, you can't determine the best.

Having said all that, any time you concatenate Strings, you may want to think about what you are doing. any time you see

String finalString = string1 + string2 + string3 + string4...

your going to be creating all kinds of unnecesary String objects you are not aware of - there's no avoiding this. Using a StringBuffer for the concatenation then converting that to a String would probably be better.

But, for a beginner, the added complexity of using a StringBuffer may not be worth it. Or, if the concatenation will only ever happen once in your program, it may not matter.

Software design is all about tradeoffs, and analysis of the specific situation for what will most likely happen and what COULD happen.

Hm, that seems rather misleading to me. The times are so short that random variations in JVM startup effects are much more significant than anything else. Also, the time to write to System.out is probably much more significant than creating the string. Unless maybe that was the point, sort of? But again, random variation in startup effects will probalby make that very hard to see. Also, using "I " + "like " + "pie." isn't representative of string concatenation in general, since it's a compile-time constant expression and is replaced at compile time with a single constant: ""I like pie."

Here's a somewhat fairer comparison of the two:

[ November 08, 2007: Message edited by: Jim Yingst ]

"I'm not back." - Bill Harding, Twister

Adam Schaible
Ranch Hand

Joined: Oct 04, 2007
Posts: 101

posted Nov 09, 2007 08:26:00

0

When I ran your example, here was the output:

After running this 10 or so times, StringBuilder was never faster than +.

My point was that all of those other things you mentioned are a much larger factor than using + or using StringBuilder, and that often times people "optimize" code and just make it slower.

I do agree, though, my test was more biased - but the difference is negligable in either case.

Sun introduced the StringBuilder class in J2SE 5.0, which is almost the same as StringBuffer, except it's not thread-safe. Thread safety is usually not necessary with StringBuffer, since it is seldom shared between threads. When Strings are added using the + operator, the compiler in J2SE 5.0 and Java SE 6 will automatically use StringBuilder. If StringBuffer is hard-coded, this optimization will not occur.

[ November 09, 2007: Message edited by: Joanne Neal ]

Joanne

Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

posted Nov 09, 2007 11:50:00

0

I should have used a larger value for MAX. I think if you add a zero (or maybe two zeros), you will see the two times are much closer, relatively. With times under a second, we're still seeing significant JVM startup time effects. Probably.

Anyway, yes, the point is that ultimately the difference between these two techniques is negligible. At least for the way the code has been written here, where the complete String is calculated in just one line. If the computation is spread across multiple lines (or one line is repeated in a loop), then StringBuilder starts to become much better. For example:

Here the StringBuilder version is much, much faster. (Adam probably already knows this, but I include it for others who are learning about these differences.) It may be instructive to try to figure out why there is such a huge difference in the performance of these two methods, as it gives a good understanding of when you really, really should use StringBuilder.

The article linked by Joanne has some nice additional examples.

[Adam]: This would fall into the lines of premature optimization - especially considering the IBM 1.5 compiler will do it automatically anytime you have string + string.

A minor bit of trivia: I've been told by someone who worked on IBM's JDK 5 compiler that it does not use StringBuffer or StringBuilder for String concatenation when the + operator is used. Instead they use their own custom class to do this. Perhaps this custom class is slightly more efficient than Sun's classes. Or perhaps it has some other benefit; I don't know. I suspect it makes little difference most of the time. [ November 09, 2007: Message edited by: Jim Yingst ]

Adam Schaible
Ranch Hand

Joined: Oct 04, 2007
Posts: 101

posted Nov 09, 2007 11:52:00

0

Originally posted by Joanne Neal:

[ November 09, 2007: Message edited by: Joanne Neal ]

So this got me a bit interested in what was happening.. Considering Jim's post about how "I like pie." would be changed to a compile time constant, and then how the compiler would replace it with StringBuiler...

It turns out that compile time constant outweighs stringbuilder. Here's the javap output:

I am doing an application code review which has the problems of OutOfMemoryError.There are many String concatenation operation done in the code by using + operator.Can that be contributing towards OutOfMemoryError? As someone said "+" operator creates many string objects,will this problem be reduced if we use StringBuffer.append method? By reading this thread,I understand there is not much difference in performance.But what about object creation?

Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

posted Nov 12, 2007 13:50:00

0

[Jitesh]: By reading this thread,I understand there is not much difference in performance.

If you read the whole thread, you will see that under certain circumstances there can be a huge difference. We don't know enough about how the concatenation is used in your code to see whether that applies here.

There are many String concatenation operation done in the code by using + operator.Can that be contributing towards OutOfMemoryError?

I think that's unlikely. The concatenation may degrade performance by creating a lot of temporary extra objects, but those objects should all available for garbage collection. If you're getting OutOfMemoryError, it's because something cannot be collected. You probably need to look elsewhere.

Jitesh Sinha
Ranch Hand

Joined: Jun 19, 2004
Posts: 146

posted Nov 12, 2007 14:22:00

0

Jim :-

I think that's unlikely. The concatenation may degrade performance by creating a lot of temporary extra objects, but those objects should all available for garbage collection. If you're getting OutOfMemoryError, it's because something cannot be collected. You probably need to look elsewhere.

In that case,if too many objects are created before GC thread starts to run,we shld get OutOfMemoryError.Is that correct?

Jim Yingst
Wanderer
Sheriff

Joined: Jan 30, 2000
Posts: 18671

posted Nov 12, 2007 14:54:00

0

No, because if that happens, the system will run full GC before it throws an OutOfMemoryError.