本文介绍了是否StringBuilder的使用比字符串连接更多的内存?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道了明显的性能优势,使用StringBuilder是在C#,但是是什么样的记忆区别?

I know the obvious performance advantage to using the StringBuilder is in C#, but what is the memory difference like?

是否StringBuilder的使用更多的内存?作为一个侧面说明,有什么本质上是做的StringBuilder什么不同,使得它如此之快?

Does the StringBuilder use more memory? and as a side note, what essentially does the stringbuilder do differently that makes it so much faster?

推荐答案

简短的回答:的StringBuilder 是在你的连接字符串中的任意数的情况下适当的你不知道在编译时。

Short answer: StringBuilder is appropriate in cases where you are concatenating an arbitrary number of strings, which you don't know at compile time.

如果您的的知道你在编译的时候什么相结合的字符串,的StringBuilder 基本上是没有意义的,你不需要它的动态调整能力。

If you do know what strings you're combining at compile time, StringBuilder is basically pointless as you don't need its dynamic resizing capabilities.

例1:你想猫,狗和鼠标相结合。这正是11个字符。你可以简单地分配长度11的char [] 阵列,并与这些字符串中的字符填充它。实际上,这就是 string.Concat 一样。

Example 1: You want to combine "cat", "dog", and "mouse". This is exactly 11 characters. You could simply allocate a char[] array of length 11 and fill it with the characters from these strings. This is essentially what string.Concat does.

例2:你想加入的用户提供的字符串数目不详成一个字符串。因为数据以串连的量是预先未知的,用的StringBuilder 在这种情况下适当

Example 2: You want to join an unspecified number of user-supplied strings into a single string. Since the amount of data to concatenate is unknown in advance, using a StringBuilder is appropriate in this case.

这篇关于是否StringBuilder的使用比字符串连接更多的内存?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-26 22:36