Created
June 13, 2014 01:10
-
-
Save tlockney/c2c6f3557db208a41399 to your computer and use it in GitHub Desktop.
A simple example where basic String concatenation in Java is really better than a StringBuilder.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public class Foo { | |
static final String aConstant = "a constant"; | |
public void concatSimpleString() { | |
String aString = "one" + aConstant + "two"; | |
} | |
public void concatWithStringBuilder() { | |
StringBuilder sb = new StringBuilder(); | |
sb.append("one"); | |
sb.append(aConstant); | |
sb.append("two"); | |
sb.toString(); | |
} | |
public static void main(String[] args) { | |
Foo foo = new Foo(); | |
foo.concatSimpleString(); | |
foo.concatWithStringBuilder(); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Compiled from "Foo.java" | |
public class Foo { | |
static final java.lang.String aConstant; | |
public Foo(); | |
Code: | |
0: aload_0 | |
1: invokespecial #1 // Method java/lang/Object."<init>":()V | |
4: return | |
public void concatSimpleString(); | |
Code: | |
0: ldc #2 // String onea constanttwo | |
2: astore_1 | |
3: return | |
public void concatWithStringBuilder(); | |
Code: | |
0: new #3 // class java/lang/StringBuilder | |
3: dup | |
4: invokespecial #4 // Method java/lang/StringBuilder."<init>":()V | |
7: astore_1 | |
8: aload_1 | |
9: ldc #5 // String one | |
11: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; | |
14: pop | |
15: aload_1 | |
16: ldc #7 // String a constant | |
18: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; | |
21: pop | |
22: aload_1 | |
23: ldc #8 // String two | |
25: invokevirtual #6 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder; | |
28: pop | |
29: aload_1 | |
30: invokevirtual #9 // Method java/lang/StringBuilder.toString:()Ljava/lang/String; | |
33: pop | |
34: return | |
public static void main(java.lang.String[]); | |
Code: | |
0: new #10 // class Foo | |
3: dup | |
4: invokespecial #11 // Method "<init>":()V | |
7: astore_1 | |
8: aload_1 | |
9: invokevirtual #12 // Method concatSimpleString:()V | |
12: aload_1 | |
13: invokevirtual #13 // Method concatWithStringBuilder:()V | |
16: return | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment