Java中的串联字符串是否总是导致在内存中创建新字符串?

发布于 2021-01-31 15:30:39

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

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个新字符串,这可能会导致性能下降。是这样吗
还是编译器足够聪明,以至于我只需要一个字符串就可以了?我如何避免这样做?

关注者
0
被浏览
110
1 个回答
  • 面试哥
    面试哥 2021-01-31
    为面试而生,有面试问题,就找面试哥。

    我意识到第二种方法使用字符串连接,并将在内存中创建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
    }
    


推荐阅读
知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看