什么时候首选`StringBuilder`而不是将`String`附加到`String`? [英] When is `StringBuilder` is preferred instead appending `String` to `String`?

查看:30
本文介绍了什么时候首选`StringBuilder`而不是将`String`附加到`String`?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是添加 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.

这篇关于什么时候首选`StringBuilder`而不是将`String`附加到`String`?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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