views:

154

answers:

4

In my project there are some code snippets which uses StringBuffer objects, and the small part of it is as follows

StringBuffer str = new StringBuffer();

str.append("new " + "String()");

so i was confused with the use of append method and the + operator.

ie the following code could be written as

str.append("new ").append("String()");

So are the two lines above same?(functionally yes but) Or is there any particular usage of them? ie performance or readability or ???

thanks.

+12  A: 

In that case it's more efficient to use the first form - because the compiler will convert it to:

StringBuffer str = new StringBuffer();
str.append("new String()");

because it concatenates constants.

A few more general points though:

  • If either of those expressions wasn't a constant, you'd be better off (performance-wise) with the two calls to append, to avoid creating an intermediate string for no reason
  • If you're using a recent version of Java, StringBuilder is generally preferred
  • If you're immediately going to append a string (and you know what it is at construction time), you can pass it to the constructor
Jon Skeet
just for more reason - StringBuilder is preferred because it is not synchronized (so faster).
jowierun
A: 

The second form is most efficient in terms of performance because there is only one string object that is created and is appended to the stringbuffer. The first form creates three string objects 1) for "new" 2)for "new String" 3) for the concatenated result of 1) and 2). and this third string object is concatenated to the string buffer.

Balaji Natesan
That's what I thought...then I read Jon Skeet's answer.
Shakedown
+5  A: 

Actually the bytecode compiler will replace all string concatenation which involve non constants in a Java program with invocations of StringBuffer. That is

int userCount = 2;
System.out.println("You are the " + userCount + " user");

will be rewritten as

int userCount = 2;
System.out.println(new StringBuffer().append("You are the ").append(userCount).append(" user").toString());

That is at least what is observable when decompiling java class files compiled with JDK 5 or 6. See this post.

nicore
A: 

Unless you are working with concurrent systems, use StringBuilder instead of StringBuffer. Its faster but not thread-safe :)

It also shares the same API so its more or less a straight find/replace-

BjornS
You didnt understand the question i believe.
GK
Yea I think I might have been a bit hasty in my reply.
BjornS