Java 中的字符串连接 - 何时使用 +、StringBuilder 和 concat [英] String concatenation in Java - when to use +, StringBuilder and concat

查看:24
本文介绍了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.

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

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