我有一条很长的字符串,不适合屏幕的宽度。例如。
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 个新字符串,这可能会导致性能下降。是这样吗?或者编译器是否足够聪明,能够弄清楚我所需要的实际上只是一个字符串?我怎样才能避免这样做呢?
我意识到第二种方法使用字符串连接,并将在内存中创建 5 个新字符串,这可能会导致性能下降。
不,不会。由于这些是字符串文字,因此将在编译时对它们进行求值,并且只有一根弦将被创建。这是定义在Java 语言规范 #3.10.5 http://docs.oracle.com/javase/specs/jls/se7/html/jls-3.html#jls-3.10.5:
长字符串文字始终可以分解为较短的片段,并使用字符串连接运算符 + 编写为(可能带括号的)表达式
[...]
此外,字符串文字始终引用 String 类的同一个实例。
- 由常量表达式(第 15.28 节)计算的字符串在编译时计算,然后将其视为文字。
- 在运行时通过连接计算的字符串是新创建的,因此是不同的。
Test:
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
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)