1. 字符串常量相加,jvm 会进行优化,不会创建 StringBuilder 对象
1 String a = "Hello" + "world" + "!";
2. 字符串变量加上常量,会创建 StringBuilder 对象,然后调用 append 方法
1 String a = "Hello"; 2 a += "top"; 3 a += "bottom";
可以看到,两个加号,创建了两个 StringBuilder 对象
3. for 循环中的字符串变量加上常量,会被优化成 StringBuilder.append(),多次相加只会创建一个 StringBuilder 对象
1 String a = "Hello"; 2 for (int i = 0; i < 5; i++) { 3 a += "world"; 4 }
IDEA 中也会进行提示:
原文:https://www.cnblogs.com/ainsliaea/p/10696191.html