This week's book giveaway is in the OCAJP 8 forum. We're giving away four copies of OCA Java SE 8 Programmer I Study Guide and have Edward Finegan & Robert Liguori on-line! See this thread for details.
Hi, I've always had a nagging question about StringBuffers. Is the following initialization an okay thing to do? Or am I creating a bunch of unneccessary string objects -- where a and b are runtime variables, like request parameters? String a = "the"; String b = "a"; StringBuffer s = new StringBuffer(a + " dog ate " + b + " bone."); Or would I be better off doing: StringBuffer s = new StringBuffer(25); s.append(a); s.append(" dog ate "); s.append(b); s.append(" bone."); Or does it matter? I tend to use the first when building StringBuffers from variables, but am afraid I am creating a lot of extra strings... Thanks, --jeff
I am not really sure on this one. It may not really matter though, because I know when you concatenate/create strings using the "+" sign, it actually uses a StringBuffer object in the background to get it's job done.
Bosun (SCJP, SCWCD)
So much trouble in the world -- Bob Marley
Hello, By no means do I pretend to be an authority on efficiency. In that light, here are my two cents... From the API Specification for StringBuffer:
String buffers are used by the compiler to implement the binary string concatenation operator +. For example, the code: x = "a" + 4 + "c" is compiled to the equivalent of: x = new StringBuffer().append("a").append(4).append("c").toString()
Looking further at the documentation, StringBuffer.append(Object - or String) creates a new StringBuffer object. So, it would seem to me, that looking at the first style: StringBuffer s = new StringBuffer(a + " dog ate " + b + " bone."); a + " dog ate " + b + " bone." creates one new String object from this: new StringBuffer.append(a).append(" dog ate ").append(b).append(" bone.") while creating 5 new StringBuffer objects (one from the implicit call to new StringBuffer plus one for each call to append) plus one more for your explicit call to new StringBuffer(String) - bringing the total to 6 StringBuffer objects. Now, your second style: StringBuffer s = new StringBuffer(25); s.append(a); s.append(" dog ate "); s.append(b); s.append(" bone."); would seem to create first one StringBuffer from new StringBuffer(int) and then one more for each call to append - a total of 5 StringBuffer objects and no "extra" String objects. Of course, I don't know what I'm talking about. Good Luck, -Dirk Schreckmann
Your second implementation would be the best route. Later on, when you use strings *cough* JavaMail *cough* you'll be happy you know StringBuffer rather well. From my understanding, it's the most efficent way to create and include multiple strings.