I realized that the second way uses string concatenation and will create 5 new strings in memory and this might lead to a performance hit.
不,不会.由于这些是字符串文字,因此它们将在编译时进行评估,并且只会创建一个字符串.这在Java Language Specification #3.10.5中定义:
A long string literal can always be broken up into shorter pieces and written as a (possibly parenthesized) expression using the string concatenation operator +
[…]
Moreover, a string literal always refers to the same instance of class String.
Strings computed by constant expressions (§15.28) are computed at compile time and then treated as if they were literals.
Strings computed by concatenation at run-time are newly created and therefore distinct.
测试:
public static void main(String[] args) throws Exception {
String longString = "This string is very long.";
String other = "This string" + " is " + "very long.";
System.out.println(longString == other); //prints true
}
然而,下面的情况是不同的,因为它使用一个变量 – 现在有一个连接,并创建了几个字符串:
public static void main(String[] args) throws Exception {
String longString = "This string is very long.";
String is = " is ";
String other = "This string" + is + "very long.";
System.out.println(longString == other); //prints false
}