字符串和字符串生成器之间的区别
我怀疑是否使用字符串或字符串生成器在 mvc 的页面中附加 html 元素,如“div”和其他元素。对于这个事情还有其他方法吗?
谢谢。
I am having doubt in whether to use string or string builder to append html elements like "div" and others in my page in mvc. Is there any other approach for this thing.
Thanks.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(7)
我读到,当您预测有超过 6 个串联时,Microsoft 建议使用 StringBuilder。
I read that Microsoft recommends using StringBuilder when you predict to have more then 6 concatenations.
StringBuilder
是正确的选择。String
保存对不可变(固定)字符串的引用,并且附加到字符串的效率非常低。如果您的目的是重复执行附加操作,那么这正是StringBuilder
的设计目的。StringBuilder
is the way to go. AString
holds a reference to an immutable (fixed) string, and appending to a string is horribly inefficient. If your intention is to repeated perform appends then this is exactly what theStringBuilder
was designed for.如果您经常更改字符串(添加、删除、更改、替换字符),因为它更高效。如果你做简单的操作,你应该使用字符串。
string 的问题是它是不可变的,因此操作
会导致创建文本变量的新实例。如果您对字符串类执行许多操作,那么您将拥有许多字符串对象的实例。
You should use StringBuilder if you change string a lot (add, remove, change, replace characters) because it's more efficient. If you do simply operation you should use string.
The problem with string is that it's immutable, so operatrion
causes that the new instance of the text variable will be created. If you do many operation on string class then you will have many instances of string objects.
每当执行附加文本时,都应该使用 stringbuilder。
使用字符串会重复创建字符串的新实例,因此效率低下。
Whenever you have perform appending texts, you should always use stringbuilder.
Using string would repeatedly create new instances of a string and hence inefficient.
查看这篇文章以了解有关以下内容的深入知识: 为什么使用 StringBuilder 而不是字符串来获得更好的性能
check this post for the depth knowledge about : Why to use StringBuilder over string to get better performance
老实说,最后说一些不寻常的话这真的不重要。差异是如此之小,以至于您不应该关心这一点,而应该将时间投入到其他有影响的事情上。
查看 Jeff 的这篇文章,其中解释了所有这些(也是在 Web 环境中,当他创建 StackOverflow 时)。
关于为什么不这样做的恐怖编码文章不管你如何创建字符串
To be honest and saying something unusual at the end it really does not matter. The differences are so small that you shouldn't care about this and you should invest the time in other things that make difference.
Check this article of Jeff where all this is explained (also in a web environment, when he was creating StackOverflow).
Coding horror article about why does not matter how do you create strings
当需要多于一根弦时,可以使用弦建造器
连接起来。
StringBuilder 效率更高,因为它确实
包含可变字符串缓冲区。 .NET 字符串是不可变的
这就是创建新字符串对象的原因
每次我们更改它(插入、追加、删除等)时。
String bulider Can Be Used When More than One String to be
concatenated.
StringBuilder which is more efficient because it does
contain a mutable string buffer. .NET Strings are immutable
which is the reason why a new string object is created
every time we alter it (insert, append, remove, etc.).