Java 中的字符串连接 - 何时使用 +、StringBuilder 和 concat

问题描述:

我们什么时候应该使用 + 来连接字符串,什么时候首选 StringBuilder,什么时候用 concat 合适.

When should we use + for concatenation of strings, when is StringBuilder preferred and When is it suitable to use concat.

我听说 StringBuilder 更适合用于循环内的串联.为什么会这样?

I've heard StringBuilder is preferable for concatenation within loops. Why is it so?

谢谢.

我倾向于在关心性能的代码路径上使用 StringBuilder.循环内重复的字符串连接通常是一个不错的选择.

I tend to use StringBuilder on code paths where performance is a concern. Repeated string concatenation within a loop is often a good candidate.

喜欢 StringBuilder 的原因是 +concat 每次调用它们时都会创建一个新对象(提供右侧参数不为空).这可以很快加起来很多对象,几乎所有这些都是完全没有必要的.

The reason to prefer StringBuilder is that both + and concat create a new object every time you call them (provided the right hand side argument is not empty). This can quickly add up to a lot of objects, almost all of which are completely unnecessary.

正如其他人指出的那样,当您在同一个语句中多次使用 + 时,编译器通常可以为您优化它.但是,根据我的经验,当串联发生在单独的语句中时,此论点不适用.它当然对循环没有帮助.

As others have pointed out, when you use + multiple times within the same statement, the compiler can often optimize this for you. However, in my experience this argument doesn't apply when the concatenations happen in separate statements. It certainly doesn't help with loops.

说了这么多,我认为首要任务应该是编写清晰的代码.有一些很棒的 Java 分析工具(我使用 YourKit),它们可以很容易地查明性能瓶颈并优化重要的部分.

Having said all this, I think top priority should be writing clear code. There are some great profiling tools available for Java (I use YourKit), which make it very easy to pinpoint performance bottlenecks and optimize just the bits where it matters.

附言我从来不需要使用 concat.

P.S. I have never needed to use concat.