+ =比concat更有效吗? [英] Is += more efficient than concat?

查看:78
本文介绍了+ =比concat更有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在阅读团队中其他开发人员生成的代码,他们似乎更喜欢使用 + = 进行字符串连接,而我更喜欢使用 .concat()因为感觉更容易阅读.

I've been reading code produced by other developers on my team, they seem to favor using += for String concatenation, whereas I prefer using .concat() as it feels easier to read.

我正在尝试准备一个论点,说明为什么使用 .concat()更好,而且我想知道两者之间的效率是否存在差异?

I'm trying to prepare an argument as to why using .concat() is better, and I'm wondering, is there any difference in efficiency between the two?

我们采用哪个选项应该"?

Which option "should" we be taking?

public class Stuff {

    public static void main(String[] args) {

        String hello = "hello ";
        hello += "world";
        System.out.println(hello);

        String helloConcat = "hello ".concat("world");
        System.out.println(helloConcat);
    }
}

推荐答案

由于字符串在Java中是不可变的,因此在执行 + + = concat(String),将生成一个新的String.字符串越大,花费的时间越长-要复制的内容更多,并且会产生更多的垃圾.

Since String is immutable in java, when you do a +, += or concat(String), a new String is generated. The bigger the String gets the longer it takes - there is more to copy and more garbage is produced.

例如,当今的Java编译器会优化您的字符串连接以使其达到最佳状态,例如

Today's java compilers optimizes your string concatenation to make it optimal, e.g.

System.out.println("x:"+x+" y:"+y);

编译器将其生成为:

System.out.println((new StringBuilder()).append("x:").append(x).append(" y:").append(y).toString());

我的建议是编写易于维护和阅读的代码.

My advice is to write code that's easier to maintain and read.

此链接显示 StringBuilder vs StringBuffer vs String.concat的性能-做对了

这篇关于+ =比concat更有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆