senyor / generate-tostring

Automatically exported from code.google.com/p/generate-tostring
0 stars 0 forks source link

Use StringBuilder instead of string concatenation #24

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
Generated toString method should use stringbuilder to build the resulting
representation instead of string concatenation. Example:

public class SessionUser {
 // ... fields etc
public String toString() {
   StringBuilder sb = new StringBuilder("SessionUser{");
   sb.append("language='").append(language).append('\'');
   sb.append(", login='").append(login).append('\'');
   sb.append("}");
}
}

The reason is that string concatenation creates a huge amount of
unnecessary string objects in memory since strings are immutable.

Also note the use of StringBuilder and not StringBuffer since the latter
includes theread safety overhead which is not necessary here. However it
might be appropriate to check the jvm version since StringBuilder is
available starting Java 1.5

Original issue reported on code.google.com by lighteater on 16 Oct 2008 at 9:55

GoogleCodeExporter commented 8 years ago
There is a template with the StringBuilder out-of-the-box. See the settings 
where you
can change the default template to use, so you can replace the + with 
stringbuilder.

Original comment by claus.ib...@gmail.com on 27 Oct 2008 at 8:11

GoogleCodeExporter commented 8 years ago
Lets keep the current default. People can just change the template of choice as 
default to use.

Original comment by claus.ib...@gmail.com on 26 Dec 2009 at 4:01