什么时候首选`StringBuilder`而不是将`String`附加到`String`?什么时候、而不是、首选、StringBuilder

2023-09-07 02:25:48 作者:我们正年轻 有何不可

以下是添加 String 的两种方法:

Below are two ways how to append String:

String firstString = "text_0";
String secondString = "text_1";
String resultString = firstString + secondString;

StringBuilder sb = new StringBuilder();
sb.append(firstString).append(secondString);
String resultString = sb.toString();

我的问题是 - 什么时候使用 StringBuilder 更有效?假设有 10 个字符串,我需要创建其中一个.

My question is - when is more effective to use StringBuilder? Let's say there are 10 strings, and I need to create one of them.

推荐答案

因为 StringBuilder 可以追加"一个字符串,而不是每次创建新对象时连接两个字符串.即使您将 += 运算符与字符串一起使用,也会创建一个新对象.仅当您尝试连接大量字符串时,此优势才会变得相关.If 也被认为更具可读性.

Because StringBuilder can "append" a string instead of concatenating two strings each time creating a new object. Even if you use += operator with Strings a new object is created. This advantage will only become relevant once you try to concatenate a great number of strings. If is also consiedered a bit more readable.