Useful Tips : StringBuilder and Java String Concatenation

As you certainly now, string concatenation in Java can be achieved using the « + » operator like that :

String parText = "This " + "is " + "a full text";
parText = parText + " in a new String object";

But each time you try to concat the string in a new line a new String object is created, therefor the String concatenation may end up as being a performance issue.

To fix this we use two types of objects : StringBuilder and StringBuffer. Then you can translate your String (e.g. a SQL Query) into :

StringBuilder stb = new StringBuilder();
stb.append("This ");
stb.append("is ");
stb.append("a full text");
stb.append(" in a new String object");

The main differences between StringBuilder and StringBuffer is that the last one is synchronized and may be used in a multi-threaded context while the other one won’t have any type of synchronization. Luckily when you try to concatenate multiple string items, Eclipse IDE, (if you ask it by typing Ctrl + 1), will ask you if you need to translate it to a StringBuilder object :

StringBuilder

But nowadays, if you’re careful and know what you’re doing, you can avoid typing this kind of « ultra verbose » way of dealing with strings. Actually since Java 1.5 String concatenations when they’re done on a whole line, are directly translated by Java Compiler, but if you jump onto another line and keep on concatenating the same String, optimization will be lost. E.g. :

// this way
StringBuilder stb = new StringBuilder();
stb.append("This ");
stb.append("is ");
stb.append("a full text");
stb.append(" in a new String object");
// and this one are equivalent
String parText = "This " + "is " + "a full text" + " in a new String object";

// but this one isn't :
String parText2 = "This " + "is " + "a full text";
parText2 = parText2 + " in a new String object";

Publicité

Votre commentaire

Entrez vos coordonnées ci-dessous ou cliquez sur une icône pour vous connecter:

Logo WordPress.com

Vous commentez à l’aide de votre compte WordPress.com. Déconnexion /  Changer )

Photo Facebook

Vous commentez à l’aide de votre compte Facebook. Déconnexion /  Changer )

Connexion à %s

%d blogueurs aiment cette page :