Even a chimp can write code

Saturday, January 22, 2005

When the + operator for concatenating Strings is a better option

Simple but not widely understood fact: the + operator for String concatenation is your best option, an order of magnitude better than StringBuffer.append(...), when the your String value resolves at compile time.

Take this situation

String str = "This " + " is " + " a " + " test " + " String.";

which represents a rather simplistic example of a composite string constructed from a bunch of (predictable) strings. This will be resolved by the compiler to

String str = "This is a test String.";

even though you used the + operator to delineate the individual strings.

Update [Jan 24, 2005]: Take a look at the bytecode for a class that declares and initializes two strings str1 (4 through 6) and str2 (7 through 39), one with each approach:

public class TestStringConcat extends java.lang.Object{
public TestStringConcat();
0: aload_0
1: invokespecial #1; //Method java/lang/Object."":()V
4: ldc #2; //String This is a test String.
6: astore_1
7: new #3; //class StringBuffer
10: dup
11: ldc #4; //String This
13: invokespecial #5; //Method java/lang/StringBuffer."":(Ljava/lang/String;)V
16: ldc #6; //String is
18: invokevirtual #7; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
21: ldc #8; //String a
23: invokevirtual #7; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
26: ldc #9; //String test
28: invokevirtual #7; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
31: ldc #10; //String String
33: invokevirtual #7; //Method java/lang/StringBuffer.append:(Ljava/lang/String;)Ljava/lang/StringBuffer;
36: invokevirtual #11; //Method java/lang/StringBuffer.toString:()Ljava/lang/String;
39: astore_2
40: return


Go ahead, write a small for-loop and test this and then compare it with the StringBuffer.append(String) method. Of course, the StringBuffer does far better in runtime String resolution situations. But you already knew that.

Email this | Bookmark this


  • not sure what was the point here

    By Blogger lemonj, at January 24, 2005 at 12:01 AM  

  • You mean apart from the fact that there is a flaw in absolute certitude ('The + operator is inefficient') or that compile-time safeguards can be better than runtime ones when predictability exists?

    I posted this because I made the mistake of creating a StringBuffer to hold a large String (broken into sub-strings to improve readability) but hastily corrected my course on realizing the flaw in my premise.

    By Blogger Ashish, at January 24, 2005 at 10:31 AM  

  • How about we concate strings with value?

    I think it still useful in some case...

    By Blogger Carfield Yim, at January 24, 2005 at 8:54 PM  

Post a Comment | Home | Inference: my personal blog