In Java, StringBuilder Object is implicitly used when a String variable is operated by "+=".
Example
String s = "hoge";
s += "fuga";
s += "piyo";
The above code will be compiled to the below code.
String s = "hoge";
s = (new StringBuilder(String.valueOf(s))).append("fuga")
.toString();
s = (new StringBuilder(String.valueOf(s))).append("piyo")
.toString();
This is a waste of machine resource, hence the code should be written, like
StringBuilder sb = new StringBuilder("hoge");
sb.append("fuga");
sb.append("piyo");
String s = sb.toString();
Or, it can be written more simply
String s = new StringBuilder("hoge").append("fuga").append("piyo")
.toString();
Reference
https://www.ne.jp/asahi/hishidama/home/tech/java/string.html
https://gihyo.jp/book/2014/978-4-7741-6685-8
Top comments (2)
I think you might have misunderstood what the compilation step actually does: when you have lots of string concatenations, the compilation step will optimise that into a StringBuilder-based approach. The point there is that you no longer need to (always) do these kinds of micro-optimisations yourself. You can rely on the compiler.
I got that putting the name of a programming language after 3 times of ` produces colorful codes.