编译器对常量字符串拼接的优化

测试代码:

package com.example.springboot.codedemo;

/**
 * 测试常量字符串拼接
 */
public class StringTest {

    public static void main(String[] args) {
        String c = "a" + "b";
        String f = "ab";
        System.out.println("c==f:" + (c == f));
    }
}

输出结果为:
在这里插入图片描述
编译后内容如下:

package com.example.springboot.codedemo;

public class StringTest {
    public StringTest() {
    }

    public static void main(String[] args) {
        String c = "ab";
        String f = "ab";
        System.out.println("c==f:" + (c == f));
    }
}

从编译后结果可以发现,变量c的字面量直接变为了”ab”,编译器已经为我们计算好了。

看下相关的部分字节码文件,如下:
在这里插入图片描述
以上的部分字节码表示把常量池的第2项存入第1个局部变量中,再把常量池的第2项存入第2个局部变量中,而常量池的第2项是什么,可以看看,如下:
在这里插入图片描述
说明了在编译时,字符串连接已经完成。

总结

所以对于常量字符串的拼接,不管拼接的多长都没事,因为编译时就会帮忙计算好了。

猜你喜欢

转载自blog.csdn.net/weixin_38106322/article/details/108269818