java - 在 Java 中连接字符串是否总是会导致在内存中创建新字符串?

标签 java string compiler-construction string-concatenation

我有一个不适合屏幕宽度的长字符串。例如。

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/

相关文章:

控制台中的 Python\xYZ 字符

c - 将 C 代码转换为 x86 汇编的简单方法?

java - 为什么 Java 8 使用 null 时,Guava 的Optional 使用抽象类?

java - Android-空指针异常反复崩溃

c# - 修改字符串列表以仅包含最大长度为 n 的字符串(使用 Linq)

PHP 从字符串中解析日期

c++ - 查看编译器扩展代码 - C++

compiler-construction - 为 TI-84 Plus 银版计算器编译 8xk 程序

如何让IntelliJ编辑器永久性显示代码行数

Java 平均水平及以上