字符串串联分配有效吗? [英] Is String concatenation on assignment efficient?

查看:101
本文介绍了字符串串联分配有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道使用"+"串联运算符来构建字符串效率很低,这就是为什么建议使用StringBuilder类的原因,但是我想知道这种模式是否也效率低下?

I know that using the "+" concatenation operator for building strings is very inefficient, and that is why it is recommended to use the StringBuilder class, but I was wondering if this kind of pattern is inefficient too?

String some = a + "\t" + b + "\t" + c + "\t" + d + "\t" + e;

我猜这里编译器会优化分配,还是不会?

I guess here the compiler will optimize the assignment fine, or not?

推荐答案

编译器将内联此特定示例:

This particular example will be inlined by the compiler:

String a = "a";
String b = "bb";
String c = "ccc";
String some = a + "\t" + b + "\t" + c;

Java 9+将使用将invokedynamic与makeConcatWithConstants 使其高效.根据javap -v输出:

Java 9+ will inline this using invokedynamic with makeConcatWithConstants making it efficient. As per javap -v output:

Code:
  stack=3, locals=5, args_size=1
     0: ldc           #2                  // String a
     2: astore_1
     3: ldc           #3                  // String bb
     5: astore_2
     6: ldc           #4                  // String ccc
     8: astore_3
     9: aload_1
    10: aload_2
    11: aload_3
    12: invokedynamic #5,  0              // InvokeDynamic #0:makeConcatWithConstants:(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;)Ljava/lang/String;
    17: astore        4
    19: return

但是,如果a bc是编译时常量,则编译器将进一步优化代码:

However if the a b and c are compile time constants compiler will further optimize the code:

final String a = "a";
final String b = "bb";
final String c = "ccc";
String some = a + "\t" + b + "\t" + c;

some将被加载一个常量值:

and some will be loaded with a constant value:

Code:
  stack=1, locals=5, args_size=1
     0: ldc           #2                  // String a
     2: astore_1
     3: ldc           #3                  // String bb
     5: astore_2
     6: ldc           #4                  // String ccc
     8: astore_3
     9: ldc           #5                  // String a\tbb\tccc
    11: astore        4
    13: return

在其他情况下,例如for循环,编译器可能无法生成优化的代码,因此StringBuilder可能会更快.

In other circumstances e.g. for loop the compiler might not be able to produce optimized code so StringBuilder might be faster.

这篇关于字符串串联分配有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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