何时使用 StringBuilder? [英] When to use StringBuilder?

查看:27
本文介绍了何时使用 StringBuilder?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
String vs StringBuilder

我刚刚重温了一些我用来学习 VB.NET 的书.我不确定我的脑子里是否有这个,了解 StringBuilder 是如何/什么是.

I just revisited some of the books that I used to pick up VB.NET. I am not sure I've got this in my head, understand how/what StringBuilder is.

使用指南是什么?如果要连接 2 个字符串或 50 个字符串,最好使用它吗?

What is the guidance for using? Is it best to use it if you are are concatenating 2 strings or 50?

或者当总字符串长度大于 128 个字符时?

Or when the the total string length is greater than 128 characters?

或者,当您使用它来将字符串相加在一起时,您是否会看到性能优势?

Or will you see a performance benefit whenever you use it to add strings together?

在哪种情况下,使用 StringBuilder 实例构建 SQL 语句比 string.format("Select * from x where y = {0}",1) 更好?

In which case is it better to use a StringBuilder instance to build a SQL statement than string.format("Select * from x where y = {0}",1)?

我一直觉得声明另一个变量并包含名称空间对于小字符串连接没有好处,但我现在不确定.

It's always struck me that declaring another variable and including a name space is not beneficial for small string concatenations, but I am not sure now.

抱歉,很多文档都告诉您该使用什么,而不是最好的.

Sorry, lot of documentation tells you what to use, just not what's best.

推荐答案

我有一个 关于这个主题的文章.总结(从页面底部复制):

I've got an article on this very topic. In summary (copied from the bottom of the page):

  • 当您在一个非平凡的循环中进行连接时,一定要使用 StringBuilder - 特别是如果您不确定(在编译时)您将通过循环进行多少次迭代.例如,一次读取一个文件,使用 += 运算符构建一个字符串可能是性能自杀.
  • 当您可以(可读地)指定需要在一个语句中连接的所有内容时,一定要使用连接运算符.(如果您有一系列要连接的内容,请考虑显式调用 String.Concat - 如果需要分隔符,请考虑调用 String.Join.)
  • 不要害怕将文字分解成几个串联的位 - 结果将是相同的.例如,您可以通过将长文字分成多行来提高可读性,而不会影响性能.
  • 如果您需要连接的中间结果而不是提供下一次连接迭代,StringBuilder 不会帮助您.例如,如果您从一个名字和一个姓氏建立一个全名,然后在最后添加第三条信息(可能是昵称),那么如果您不这样做,您只会从使用 StringBuilder 中受益需要(名字 + 姓氏)字符串用于其他目的(就像我们在创建 Person 对象的示例中所做的那样).
  • 如果您只需要执行几个串联,并且您真的想在单独的语句中执行它们,那么走哪条路并不重要.哪种方式更有效将取决于所涉及的字符串大小的串联次数,以及它们串联的顺序.如果您真的认为那段代码是性能瓶颈,请以两种方式对其进行分析或基准测试.

这篇关于何时使用 StringBuilder?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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