我有一个不适合屏幕宽度的长字符串。例如。
String longString = "This string is very long. It does not fit the width of the screen. So you have to scroll horizontally to read the whole string. This is very inconvenient indeed.";
为了方便阅读,我想到了这样写——
String longString = "This string is very long." +
"It does not fit the width of the screen." +
"So you have to scroll horizontally" +
"to read the whole string." +
"This is very inconvenient indeed.";
但是,我意识到第二种方法使用字符串连接,会在内存中创建 5 个新字符串,这可能会导致性能下降。是这样吗?或者编译器是否足够聪明,可以找出我真正需要的只是一个字符串?我怎么能避免这样做呢?
最佳答案
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
}
关于java - 在 Java 中连接字符串是否总是会导致在内存中创建新字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11989261/