Java中的字符串连接 - 何时使用+,StringBuilder和concat [英] String concatenation in Java - when to use +, StringBuilder and 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.
P.S。我从来不需要使用 concat
。
P.S. I have never needed to use concat
.
这篇关于Java中的字符串连接 - 何时使用+,StringBuilder和concat的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!