Answer the question
In order to leave comments, you need to log in
If StringBuider is preferred over String, then what are the cons of using StringBuilder always and everywhere instead of String?
The first question is in the title.
Second, why doesn't the Java compiler automatically optimize concatenation operations and so on using StringBuilder? Or can it be turned on somehow?
Answer the question
In order to leave comments, you need to log in
Programming is an engineering discipline. It cannot contain magic recipes that work always and everywhere. The art of an engineer in finding compromises that give the most beneficial combination of qualities in specific situations. StringBuilder
gives an advantage only when there are many operations to change the row. For example, when growing a string in a loop. In all other cases, it is StringBuilder
slower and requires more memory. Also, it is not thread-safe, but strings are.
In terms of optimization, the compiler replaces string concatenations with the StringBuilder.append() method , but only when it is certain that this will not change the execution logic. It's easy to see. Let's take this code:
public class Example {
public static String concat(String s1, String s2) {
return s1 + s2;
}
public static void main(String[] args) {
System.out.println(concat("Hello ", "World"));
}
}
public static java.lang.String concat(java.lang.String, java.lang.String);
Code:
0: new #2 // class java/lang/StringBuilder
3: dup
4: invokespecial #3 // Method java/lang/StringBuilder."<init>":()V
7: aload_0
8: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
11: aload_1
12: invokevirtual #4 // Method java/lang/StringBuilder.append:(Ljava/lang/String;)Ljava/lang/StringBuilder;
15: invokevirtual #5 // Method java/lang/StringBuilder.toString:()Ljava/lang/String;
18: areturn
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question