DEV Community

Cover image for StringBuilder is implicitly used when there is String += in Java
Yasushi Takehara
Yasushi Takehara

Posted on

StringBuilder is implicitly used when there is String += in Java

In Java, StringBuilder Object is implicitly used when a String variable is operated by "+=".

Example

String s = "hoge";
s += "fuga";
s += "piyo";
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

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();
Enter fullscreen mode Exit fullscreen mode

Or, it can be written more simply

String s = new StringBuilder("hoge").append("fuga").append("piyo")
.toString();
Enter fullscreen mode Exit fullscreen mode

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)

Collapse
 
alainvanhout profile image
Alain Van Hout

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.

Collapse
 
yasushitakehara profile image
Yasushi Takehara • Edited

I got that putting the name of a programming language after 3 times of ` produces colorful codes.