假设字符串a和b:

a += b
a = a.concat(b)

在引擎盖下,它们是一样的吗?

这里是concat反编译作为参考。我希望能够反编译+操作符以及看看它做什么。

public String concat(String s) {

    int i = s.length();
    if (i == 0) {
        return this;
    }
    else {
        char ac[] = new char[count + i];
        getChars(0, count, ac, 0);
        s.getChars(0, i, ac, count);
        return new String(0, count + i, ac);
    }
}

当前回答

我运行了类似于@marcio的测试,但使用了以下循环:

String c = a;
for (long i = 0; i < 100000L; i++) {
    c = c.concat(b); // make sure javac cannot skip the loop
    // using c += b for the alternative
}

为了更好的度量,我还添加了StringBuilder.append()。每个测试运行10次,每次运行100,000次。以下是调查结果:

StringBuilder轻松获胜。大多数运行的时钟时间结果为0,最长的运行时间为16毫秒。 A += b每次运行大约需要40000ms (40s)。 Concat每次运行只需要10000ms (10s)。

我还没有反编译类来查看内部结构或通过分析器运行它,但我怀疑a += b花了很多时间来创建StringBuilder的新对象,然后将它们转换回String。

其他回答

+运算符可以在字符串、char、integer、double或float数据类型值之间工作。它只是在连接之前将值转换为字符串表示形式。

concat操作符只能在字符串上执行。它检查数据类型兼容性,如果不匹配,则抛出错误。

除此之外,您提供的代码也做同样的事情。

注意s.concat(“hello”);当s为空时,将导致NullPointereException。在Java中,+操作符的行为通常由左操作数决定:

System . out。printin (3 + a);/ / 100

但是,字符串是个例外。如果任意一个操作数是String,则预期结果是String。这就是null被转换为“null”的原因,即使你可能期望一个RuntimeException。

基本上,+和concat方法之间有两个重要的区别。

If you are using the concat method then you would only be able to concatenate strings while in case of the + operator, you can also concatenate the string with any data type. For Example: String s = 10 + "Hello"; In this case, the output should be 10Hello. String s = "I"; String s1 = s.concat("am").concat("good").concat("boy"); System.out.println(s1); In the above case you have to provide two strings mandatory. The second and main difference between + and concat is that: Case 1: Suppose I concat the same strings with concat operator in this way String s="I"; String s1=s.concat("am").concat("good").concat("boy"); System.out.println(s1); In this case total number of objects created in the pool are 7 like this: I am good boy Iam Iamgood Iamgoodboy Case 2: Now I am going to concatinate the same strings via + operator String s="I"+"am"+"good"+"boy"; System.out.println(s); In the above case total number of objects created are only 5. Actually when we concatinate the strings via + operator then it maintains a StringBuffer class to perform the same task as follows:- StringBuffer sb = new StringBuffer("I"); sb.append("am"); sb.append("good"); sb.append("boy"); System.out.println(sb); In this way it will create only five objects.

伙计们,这就是+和concat方法的基本区别。 享受:)

我不这么想。

a.concat(b)是在String中实现的,我认为自早期java机器以来,实现没有太大变化。+操作的实现取决于Java版本和编译器。目前+是使用StringBuffer实现的,以使操作尽可能快。也许在未来,这种情况会改变。在java +的早期版本中,对字符串的操作要慢得多,因为它产生中间结果。

我猜+=是使用+实现的,并进行了类似的优化。

Tom准确地描述了+运算符的作用。它创建了一个临时的StringBuilder,添加了部分,并以toString()结束。

然而,到目前为止,所有的答案都忽略了HotSpot运行时优化的影响。具体来说,这些临时操作被认为是一种公共模式,并在运行时被更有效的机器代码所取代。

@marcio:你创建了一个微基准测试;在现代JVM中,这不是一种分析代码的有效方法。

运行时优化之所以重要,是因为一旦HotSpot开始运行,代码中的许多差异(甚至包括对象创建)就完全不同了。唯一确定的方法是在原位分析您的代码。

最后,所有这些方法实际上都非常快。这可能是一个过早优化的例子。如果您的代码连接了很多字符串,那么获得最大速度的方法可能与您选择的操作符无关,而是与您使用的算法有关!