smhy8187

 

String和StringBuilder

String和StringBuilder

1、String创建一个不可改变的对象,StringBuilder创建一个可以改变的对象。
string str1 = "a";
str1 = "b";
给str1更改值等效新建一个String对象。
string使用“=”操作符实际上就是new   string(info)

2、StringBuilder 类解决了对字符串进行重复修改的过程中创建大量对象的问题。初始化一个StringBuilder 之后,它会自动申请一个默认的StringBuilder 容量(默认值是16),这个容量是由Capacity来控制的。并且允许我们根据需要来控制Capacity的大小,也可以通过Length来获取或设置StringBuilder 的长度。

听起来好象StringBuilder比String好很多。是不是到处都用StringBuilder呢?很明显肯定不是了。要不c#也不会要这个String。
看看下面两张图片(摘自http://www.cnblogs.com/kid-li/archive/2006/10/18/532174.html):
====================================
李建忠老师讲解了一下copy-to-write技术。对于两个String类型的变量来说,如下

String str1 = “aa”;

String str2 = “aa”;

当这两个String类型变量的值相同时,实际上他们指向的是同一个内存空间,如下图:


   对于
StringBuilder对象来说是这样的,如:有两个StringBuilder对象

       StringBuilder sb1 = new StringBuilder(“aa”)

       StringBuilder sb2 = new StringBuilder(“aa”)

他们在内存中的状态如下图:
   

 

sb2变化时,只是修改sb2中指向的位置。如下图


==============================
关于这个问题,还有位高手也做了些解释:
Why string? Can't use StringBinder everywhere?
No. You can't. When initializing a StringBuilder you are going down in performance. Also many actions that you do with string can't be done with StringBinder. Actually it is used mostly for situations as explained above. Last week I show a person, who used StringBuilder to just add two strings together! its really nonsense. We must really think about the overhead of initialization. In my personal experience a StringBuilder can be used where more than four or more string concatenation take place. Also if you try to do some other manipulation (Like removing a part from the string, replacing a part in the string, etc, etc) then better not to use StringBuilder at those places. Because anyway we are creating new strings. Another important issue. We must be careful to guess the size of StringBuilder . If the size which we are going to get is more than what assigned, it must increase the size. Which will reduce the performance of it.

微软工程师还有个Advice:

if your pattern looks like:
x = f1(...) + f2(...) + f3(...) + f4(...)
 
that's one concat and it's zippy, StringBuilder probably won't help.
 
if your pattern looks like:
if (...) x += f1(...)
if (...) x += f2(...)
if (...) x += f3(...)
if (...) x += f4(...)
 then you probably want StringBuilder.

(摘自:http://blogs.msdn.com/ricom/archive/2003/12/15/43628.aspx

posted on 2008-01-15 15:39  new2008  阅读(200)  评论(0编辑  收藏  举报

导航