Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

append or + operator in StringBuffer?

Tags:

java

string

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.

like image 902
GuruKulki Avatar asked Nov 29 '22 18:11

GuruKulki


1 Answers

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
like image 142
Jon Skeet Avatar answered Dec 05 '22 01:12

Jon Skeet