If the following code:
String s = "a" + 1 + "b";// 1.
Is implemented using using StringBuilder equivalent to
String s = new StringBuilder().append("a").append(1).append("b");
then will extra objects "a" and "b" be created in 1 and why?
String concatenation using StringBuilder class StringBuilder is class provides append() method to perform concatenation operation. The append() method accepts arguments of different types like Objects, StringBuilder, int, char, CharSequence, boolean, float, double.
String is immutable whereas StringBuffer and StringBuilder are mutable classes. StringBuffer is thread-safe and synchronized whereas StringBuilder is not. That's why StringBuilder is faster than StringBuffer. String concatenation operator (+) internally uses StringBuffer or StringBuilder class.
Performance wise difference between + operator and StringBuilder. append is, + has a very small overhead of instantiating StringBuilder instance and converting result back to String object. This will reflect in the performance graph above.
Since Java 9, simple one line concatenation with "+" produces code potentially better than StringBuilder.
Your example will not actually use a StringBuilder
because none of the elements are variables. Because "a", 1, and "b" are all literals, the compiler will make a single String
for you! If, however, you included a variable in that String
concatenation, then it would use a StringBuilder
and would need separate String
s for the concatenated elements.
For your example the compiler would create a single String literal:
const #2 = String #21; // a1b
public void foo();
Code:
Stack=1, Locals=2, Args_size=1
0: ldc #2; //String a1b
2: astore_1
3: return
LineNumberTable:
line 7: 0
line 8: 3
Let's say we had instead written
public void bar(String c)
{
String s = "a" + c + "b";// 1.
}
Now the compiler will need to create a StringBuilder
, and it will use the a and b constant ASCII literals with the StringBuilder
.
const #20 = Asciz a;
const #22 = Asciz b;
public void bar(java.lang.String);
Code:
Stack=2, Locals=3, Args_size=2
0: new #2; //class java/lang/StringBuilder
3: dup
4: invokespecial #3; //Method java/lang/StringBuilder."<init>":()V
7: ldc #4; //String a
9: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava /lang/String;)Ljava/lang/StringBuilder;
12: aload_1
13: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
16: ldc #6; //String b
18: invokevirtual #5; //Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
21: invokevirtual #7; //Method java/lang/StringBuilder.toString:()Ljava/lang/String;
24: astore_2
25: return
LineNumberTable:
line 7: 0
line 8: 25
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With