在Java中使用+连接字符串 [英] Using + to concat string in Java

查看:59
本文介绍了在Java中使用+连接字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个巨大的字符串,如下所示:

  String str = aaaaaaa 
+ bbbbbbbb
+ cccccccc
....

+ zzzzzzzz; //大约200行长的

这是否浪费大量内存?将它放在一行中还是使用 StringBuilder 会更好?
这样做是为了创建一个长SQL。

解决方案

否。如果您所有的字符串都是常量(如您所问的那样),则编译器将在编译时执行连接 。这样最终会比 StringBuilder 版本表现更好。



它将使用 StringBuilder (或 StringBuffer )执行所有非恒定部分的连接。 / p>

这样的编译版本:

 字符串x = a + b; 

应与以下内容完全相同:

  String x = ab; 

请注意,非恒定部分可能意味着您有时会(很少)获得额外收入明智地使用包围的效率。例如:

  int value = ...; 
字符串x = a +值+ b + c;

...的效率低于:

  int值= ...; 
字符串x = a +值+( b + c);

...作为第一个附加项 b c 。有效版本等效于:

  int value = ...; 
字符串x = a +值+ bc;

我不记得曾经将其用作合法的微型广告,优化,但这至少是一个兴趣点。


I have a huge string as below :

String str = "aaaaaaa" 
        + "bbbbbbbb" 
        + "cccccccc" 
    .... 

        + "zzzzzzzz";  // about 200 lines long

Is it a big waste of memory? Will it be better to put it in one line or use StringBuilder? This is done to create a long sql.

解决方案

No. The compiler will perform the concatenation at compile time if all your strings are constant (as they are in your question). So that ends up performing better than the StringBuilder version.

It will use StringBuilder (or StringBuffer) to perform the concatenation of any non-constant parts otherwise.

So the compiled version of:

String x = "a" + "b";

should be exactly the same as:

String x = "ab";

Note that the "non-constant" parts can mean that you can sometimes get (very minor) extra efficiencies using bracketing wisely. For example:

int value = ...;
String x = "a" + value + "b" + "c";

... is less efficient than:

int value = ...;
String x = "a" + value + ("b" + "c");

... as the first appends "b" and "c" separately. The efficient version is equivalent tO:

int value = ...;
String x = "a" + value + "bc";

I can't remember ever seeing this used as a legitimate micro-optimization, but it's at least a point of interest.

这篇关于在Java中使用+连接字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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