Java中的串联字符串是否总是导致在内存中创建新字符串?
我的长字符串不适合屏幕的宽度。例如。
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中定义的:可以使用字符串连接运算符+
[…] 将长字符串文字始终分解成较短的片段并写为(可能带有括号)表达式,
而且,字符串文字始终始终引用String类的相同实例。- 由常量表达式(第15.28节)计算出的字符串在编译时进行计算,然后将其视为文字。
- 在运行时通过串联计算的字符串是新创建的,因此是不同的。
测试:
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中的字符串在内存中创建File对象
2021-01-30 关注 0 浏览98 1答案
-
在内存中创建了多少个字符串?
2021-01-30 关注 0 浏览83 1答案
-
在 Ruby 中修剪字符串而不创建新字符串的规范方法是什么?
2022-07-28 关注 0 浏览11 1答案
-
如何串联Java中的字符串?
2021-01-29 关注 0 浏览63 1答案
-
java中字符串常量的串联
2021-01-30 关注 0 浏览93 1答案
-
如何在Java中串联字符串数组
2021-01-30 关注 0 浏览106 1答案
-
在Java中串联空字符串
2021-02-02 关注 0 浏览68 1答案
-
加载模块时,Python文档字符串和注释是否存储在内存中?
2021-01-29 关注 0 浏览157 1答案
-
Java测试字符串是否包含数组中的任何字符串
2021-02-02 关注 0 浏览115 1答案
-
Java字符串不变性和使用相同的字符串值创建新的字符串
2021-01-29 关注 0 浏览135 1答案