[Reading notes] C# study notes eight: StringBuilder and String detailed explanation and parameter passing problem analysis


[Reading notes] C# study notes eight: StringBuilder and String detailed explanation and parameter passing problem analysis

Preface

Last time at a company meeting, a colleague shared the knowledge of windebug. I took the string string Concat splicing and then used the while(true){} infinite loop Demo to explain.
Among them, it mentioned the inefficiency of string operation on a large number of strings. I just saw a similar problem before, so I took it out and recorded it. The
content of this article: Anatomy of the parameter passing problem, detailed explanation of string and stringbuilder

1. Analysis of parameter transfer problem

For parameter passing in C#, it can be divided into four categories according to the type of parameters:

  • Pass by value of value type parameters

  • Pass by value of reference type parameters

  • Pass by reference of value type parameters

  • Pass by reference of reference type parameters

1.1 Pass by value of value type parameters

Copy code

 1 class Program 2 {3 static void Main(string[] args) 4 {  
 5 6 int addNum = 1; 7 // addNum is the actual parameter, 8 Add(addNum);  
 9 }10 11 // addnum is the formal parameter, also It is the parameter in the called method 12 private static void Add(int addnum) 13 {14 addnum = addnum + 1; 15 Console.WriteLine(addnum); 16 }17}

Copy code

For value type transfer by value, what is passed is a copy of the value type instance, that is, the formal parameter receives a copy of the actual parameter at this time, and the called method operation is a copy of the actual parameter, so it is not It does not affect the parameter values ​​in the original calling method . In order to prove this point, look at the following code and running results to understand:

Copy code

 1 class Program 2 {3 static void Main(string[] args) 4 {  
 5 // 1. Value type is passed by value 6 Console.WriteLine("Pass by value"); 7 int addNum = 1; 8 Add (addNum); 9 Console.WriteLine(addNum);    
10 11 Console.Read(); 12 }13 14 // 1. Value type is passed by value 15 private static void Add(int addnum)16 {17 addnum = addnum + 1;18 Console.WriteLine(addnum);19 }20}

Copy code

 

The result of the operation is: 
Pass by value
2
1
It can be seen from the result that its value has not changed after the addNum method is called. The call of the Add method only changes the value of addnum, a copy of addNum, so the value of addnum is changed to 2. . For specific analysis, please see the following figure:


1.2 Passing by value of reference type parameters
When the passed parameter is a reference type, what is passed and operated is a reference to an object (seeing this, some friends will think that it is not a reference at this time Why? Why is it still passed by value? For this doubt, it is indeed passed by value at this time. At this time, the address of the object passed, the address itself is also passed the value of this address, so it is still passed by value at this time), At this time, the operation of the method will change the original object. code show as below:

Copy code

 1 class Program 2 { 3     static void Main(string[] args) 4     { 
 5         // 2. 引用类型按值传递情况 6         RefClass refClass = new RefClass(); 7         AddRef(refClass); 8         Console.WriteLine(refClass.addnum); 9     }    
10      // 2. 引用类型按值传递情况11     private static void AddRef(RefClass addnumRef)12     {13         addnumRef.addnum += 1;14         Console.WriteLine(addnumRef.addnum);15     }16 }17 class RefClass18 {19     public int addnum=1;20 }

Copy code

运行结果为:
2
2
为什么此时传递引用就会修改原来实参中的值呢?对于这点我们还是参数在内存中分布图来解释下:

1.3string引用类型参数的按值传递的特殊情况
对于String类型同样是引用类型,然而对于string类型的按值传递时,此时引用类型的按值传递却不会修改实参的值,可能很多朋友对于这点很困惑,下面具体看看下面的代码:

Copy code

 1 class Program 2 { 3     static void Main(string[] args) 4     { 
 5           // 3. String引用类型的按值传递的特殊情况 6         string str = "old string"; 7         ChangeStr(str); 8         Console.WriteLine(str); 9         10     }11     12      // 3. String引用类型的按值传递的特殊情况13     private static void ChangeStr(string oldStr)14     {15         oldStr = "New string";16         Console.WriteLine(oldStr);17     }18 }

Copy code

运行结果为:

New string
old string
对于为什么原来的值没有被改变主要是因为string的“不变性”,所以在被调用方法中执行 oldStr="New string"代码时,此时并不会直接修改oldStr中的"old string"值为"New string",因为string类型是不变的,不可修改的,此时内存会重新分配一块内存,然后把这块内存中的值修改为 “New string”,然后把内存中地址赋值给oldStr变量,所以此时str仍然指向 "old string"字符,而oldStr却改变了指向,它最后指向了 "New string"字符串。所以运行结果才会像上面这样,下面内存分布图可以帮助你更形象地理解文字表述:

1.4按引用传递

不管是值类型还是引用类型,我们都可以使用ref 或out关键字来实现参数的按引用传递,然而按引用进行传递的时候,需要注意下面两点:

方法的定义和方法调用都必须同时显式使用ref或out,否则会出现编译错误

CLR允许通过out 或ref参数来实现方法重载。如:

Copy code

 1 #region CLR 允许out或ref参数来实现方法重载 2 private static void Add(string str) 3 { 4     Console.WriteLine(str); 5 } 6  7 // 编译器会认为下面的方法是另一个方法,从而实现方法重载 8 private static void Add(ref string str) 9 {10     Console.WriteLine(str);11 }12 #endregion

Copy code

按引用传递可以解决由于值传递时改变引用副本而不影响引用本身的问题,此时传递的是引用的引用(也就是地址的地址),而不是引用的拷贝(副本)。下面就具体看看按引用传递的代码:

Copy code

 1 class Program 2 { 3     static void Main(string[] args) 4     { 
 5         #region 按引用传递 6         Console.WriteLine("按引用传递的情况"); 7         int num = 1; 8         string refStr = "Old string"; 9         ChangeByValue(ref num);10         Console.WriteLine(num);11         changeByRef(ref refStr);12         Console.WriteLine(refStr);13         #endregion 14 15         Console.Read();16     }17 18     #region 按引用传递19     // 1. 值类型的按引用传递情况20     private static void ChangeByValue(ref int numValue)21     {22         numValue = 10;23         Console.WriteLine(numValue);24     }25 26     // 2. 引用类型的按引用传递情况27     private static void changeByRef(ref string numRef)28     {29         numRef = "new string";30         Console.WriteLine(numRef);31     }32 33     #endregion34 }

Copy code

运行结果为:
按引用传递的情况
10
10
new string
new string
从运行结果可以看出,此时引用本身的值也被改变了,通过下面一张图来帮忙大家理解下按引用传递的方式:



到这里参数的传递所有内容就介绍完了。总之,对于按值传递,不管是值类型还是引用类型的按值传递,都是传递实参的一个拷贝,只是值类型时,此时传递的是实参实例的一个拷贝(也就是值类型值的一个拷贝),而引用类型时,此时传递的实参引用的副本。对于按引用传递,传递的都是参数地址,也就是实例的指针。

2, string与stringBuilder的内部实现
大家应该知道如果做大量的字符串拼接的话, string的效率明显是低于stringBuilder的, 至于示例我这里就不在列出了,下面给出个链接可以查看下.
我这里只是从string和stringBuilder源码说起, 通过源代码的实现方式来说明stringBuilder为何比string效率高.

StringBuilder vs String+String(String concatenation):
通常情况下,4~8个字符串之间的连接,String+String的效率更高。
答案来自: http://stackoverflow.com/a/1612819
StringBuilder vs String.concat():
如果在编译期间不能确定要连接的字符串个数,用StringBuilder更合适。
答案来自: http://stackoverflow.com/a/4191142

下面先给出结论:

stringbuilder内部维护一个字符数组。下次追加的字符串,直接占用空余的位置。 
如果超出上限。数组增大为原来的两倍(两倍还不够就直接增大到足够宽度),然后覆盖原来的数组.

String是不可改变的。每次使用System.String类中的方法之一时,都要在内存中创建一个新的字符串对象,这就需要为该新对象分配新的空间。
在需要对字符串执行重复修改的情况下,与创建新的String对象相关的系统开销可能会非常昂贵。

那么下面就看看string和stringBuilder源码有和区别吧, 我这里是使用的Reflector查看的:
(1)string

打开Reflector,找到string类

找到Concat方法, 我们这里以Concat为例:

下面我们在看下FillStringChecked(dest, 0, str0)的实现方式:


所以看到这里结论就出来了: 当我们队字符串进行大量操作的时候, 会产生很多的新的字符串, 这些字符串会大量零碎的占据着堆空间, 大多都是生存期较短的, 会对gc产生比较大的回收压力.


(2)stringBuilder

看这个类的话,还是看一下它的源代码,以Append吧,从下面这个截图中看出来几个有意思的地方。

<1> 原来StringBuilder里面维护的是一个m_ChunkChars的字符数组。

<2> 如果当前的字符串的length<2,会直接给chunkchars数组复制,length>2的时候看到的是刚才string类中经典的wstrcpy用法,而

      这个时候ptr指向的是chunkChars[chunkLength]的首地址,而不像string中申请新的内存空间,所以从这里看,比string大大的节省

    了内存空间。




更多细节内容请看@老赵点滴 大神的博客内容吧:

重谈字符串连接性能上:http://blog.zhaojie.me/2009/11/string-concat-perf-1-benchmark.html
重谈字符串连接性能中:http://blog.zhaojie.me/2009/12/string-concat-perf-2-stringbuilder-implementations.html
重谈字符串连接性能下:http://blog.zhaojie.me/2009/12/string-concat-perf-3-profiling-analysis.html

PS:好了, 到了这里@Learning Hard的<<C#读书笔记>> 的读书笔记就分享完了. 后面开始自己学Asp.Net(以前学的是java, 接触最多的是jsp, 到了公司开始做.Net), 对于Asp.Net还不是太了解, 希望用一段时间可以掌握这个. 另外空闲时间还在读<<CLR via C#>>这本书, 很不错的一本书, 需要慢慢去消化.

Spoken Tips:
Be my guest.
Please, don’t
be polite. Boy will be boys.
Nature is hard to change!
Don't beat around the bush. Don't beat around the bush
.
Don't bury your head in the sand. Don't bury your head in the sand.
Don't evade reality. .
the Do not GET me Wrong.
Do not get me wrong
Do not get on my nerves!
Do not stir my nerves
Do not look wise.
Do not try to be smart.

Category:  C# basic seriesreading notes

Good article should  pay attention to my  favorite article  

Is a flower considered romantic


Guess you like

Origin blog.51cto.com/7592962/2543843