连接字符串最有效的方法是什么?
当前回答
除了其他答案之外,请记住StringBuilder可以被告知要分配的初始内存量。
容量参数定义了当前实例分配的内存中可以存储的最大字符数。它的值被赋给Capacity属性。如果当前实例中存储的字符数量超过了这个容量值,StringBuilder对象就会分配额外的内存来存储这些字符。 如果容量为零,则使用特定于实现的默认容量。
重复添加到未预先分配的StringBuilder可能会导致大量不必要的分配,就像重复连接常规字符串一样。
If you know how long the final string will be, can trivially calculate it, or can make an educated guess about the common case (allocating too much isn't necessarily a bad thing), you should be providing this information to the constructor or the Capacity property. Especially when running performance tests to compare StringBuilder with other methods like String.Concat, which do the same thing internally. Any test you see online which doesn't include StringBuilder pre-allocation in its comparisons is wrong.
如果你无法猜测它的大小,你可能在写一个效用函数它应该有自己的可选参数来控制预分配。
其他回答
StringBuilder.Append()方法比使用+操作符要好得多。但我发现,当执行1000个或更少的连接时,String.Join()甚至比StringBuilder更有效。
StringBuilder sb = new StringBuilder();
sb.Append(someString);
String的唯一问题。Join是指必须使用公共分隔符连接字符串。
编辑:正如@ryanversaw指出的,可以将分隔符设置为string.Empty。
string key = String.Join("_", new String[]
{ "Customers_Contacts", customerID, database, SessionID });
如果你在循环中操作,StringBuilder可能是最好的选择;它节省了定期创建新字符串的开销。在只运行一次的代码中,字符串。Concat可能没问题。
然而,Rico Mariani(。NET优化大师)做了一个测试,他在测试的最后说,在大多数情况下,他建议使用String.Format。
最有效的方法是使用StringBuilder,如下所示:
StringBuilder sb = new StringBuilder();
sb.Append("string1");
sb.Append("string2");
...etc...
String strResult = sb.ToString();
@jonezy:字符串。Concat是好的,如果你有一些小东西。但是,如果您正在连接兆字节的数据,那么您的程序可能会崩溃。
StringBuilder并不总是更快:
经验法则
当连接三个或更少的动态字符串值时,使用传统的字符串连接。 当连接三个以上的动态字符串值时,请使用StringBuilder。 当从多个字符串字面值构建一个大字符串时,可以使用@字符串字面值或内联+操作符。
大多数情况下,StringBuilder是您最好的选择,但在某些情况下,如那篇文章所示,您至少应该考虑每种情况。
下面可能是连接多个字符串的另一种解决方案。
String str1 = "sometext";
string str2 = "some other text";
string afterConcate = $"{str1}{str2}";
字符串插值
推荐文章
- 实体框架核心:在上一个操作完成之前,在此上下文中开始的第二个操作
- 如何为构造函数定制Visual Studio的私有字段生成快捷方式?
- 为什么Visual Studio 2015/2017/2019测试运行器没有发现我的xUnit v2测试
- 确定记录是否存在的最快方法
- 如何使用JSON确保字符串是有效的JSON。网
- Printf与std::字符串?
- AppSettings从.config文件中获取值
- 通过HttpClient向REST API发布一个空体
- 阅读GHC核心
- 如何检查IEnumerable是否为空或空?
- 不区分大小写的“in”
- 自动化invokerrequired代码模式
- 我如何得到一个字符串的前n个字符而不检查大小或出界?
- 没有ListBox。SelectionMode="None",是否有其他方法禁用列表框中的选择?
- 在c#代码中设置WPF文本框的背景颜色