• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

StringBuffer instantiation in a loop

 
Vincent Tomas
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello,

Would there be any problems (i.e.efficiency) with instantiating a StringBuffer in a loop?

For example:



If there are any problems, would you please let me know of a better solution.

Thank you in advance,

Vincent
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi Vincent,

Welcome to JavaRanch!

Loops don't present any special performance issues other than that the code inside of them will be executed more than once. If the loop will run 3 or 10 or 20 times, it hardly matters. If a loop is going to run a million times, then it can be worth the effort to squeeze every possible object instantiation -- explicit or implicit -- outside of the loop.

If you tell us what kind of code you're talking about, we might have some more specific advice.
 
Vincent Tomas
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Thank you Ernest for the prompt response! Wow!

My loop will loop 10,000 times. For example:

NOTE: this is a simplistic way of to convey my example. I would do it all in one method



Thanks!

Vincent
 
Ernest Friedman-Hill
author and iconoclast
Marshal
Pie
Posts: 24208
35
Chrome Eclipse IDE Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
As always, the devil is in the details, but...

If what you need is 10,000 Strings that consist of two components, then you don't have much choice, really, other than using a StringBuffer (actually, in new code, Java 5's StringBuilder is a better choice, but the APIs are identical). You could use a char[] and do the moral equivalent of append() yourself, but it would be unlikely to be worth the effort.

But if you're doing something further with 'color', such that you don't really need it as a String itself -- for example, just printing it -- then it would be better to avoid the StringBuffer here.

So I guess I'm saying that we still need more information to give a really good answer.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Note that you can simply code this as



without any performance impact. The compiler will translate that to using a StringBuilder/Buffer, anyway.

Using StringBuilder only starts to pay back when you append *to the same string* *in more than one statement*, i.e. while looping.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic