找回密码
 立即注册
首页 业界区 业界 透过WinDBG的视角看String

透过WinDBG的视角看String

赖秀竹 5 天前
摘要 : 最近在博客园里面看到有人在讨论 C# String的一些特性. 大部分情况下是从CODING的角度来讨论String. 本人觉得非常好奇, 在运行时态, String是如何与这些特性联系上的. 本文将侧重在通过WinDBG来观察String在进程内的布局, 以此来解释C# String的一些特性.
 
问题

C# String有两个比较有趣的特性.

  • String的恒定性. 字符串横定性是指一个字符串一经创建,就不可改变。那么也就是说当我们改变string值的时候,便会在托管堆上重新分配一块新的内存空间,而不会影响到原有的内存地址上所存储的值。
  • String的驻留. CLR runtime通过维护一个表来存放字符串,该表称为拘留池,它包含程序中以编程方式声明或创建的每个唯一的字符串的一个引用。因此,具有特定值的字符串的实例在系统中只有一个。
对应着两个特性, 我产生了一些疑问.

  • String的恒定性是怎么样让string进行比较的时候出现有趣的结果的? 它的比较结果为什么会与其他引用类型的结果不一样?
  • 什么样的String会被放到拘留池中?
  • 拘留池是怎样的数据结构? 它真是个Hashtable吗?
  • 驻留在拘留池内的String会不会被GC,  它的生命周期会有多长(什么时候才会被回收)?
 
String的恒定性

先看一下下面的例子 :
 
  1. private static void Comparation()
  2. {
  3.     string a = "Test String";
  4.     string b = "Test String";
  5.     string c = a;
  6.     Console.WriteLine("a vs b : " + object.ReferenceEquals(a, b));
  7.     Console.WriteLine("a vs c : " + object.ReferenceEquals(a, c));
  8.     SimpleObject smp1 = new SimpleObject(a);
  9.     SimpleObject smp2 = new SimpleObject(a);
  10.     Console.WriteLine("smp1 vs smp2 : " + object.ReferenceEquals(smp1, smp2));
  11.     Console.ReadLine();
  12. }
  13. class SimpleObject
  14. {
  15.     public string name = string.Empty;
  16.     public SimpleObject(string name)
  17.     {
  18.         this.name = name;
  19.     }
  20. }
复制代码
 
1.png

从结果上看, 虽然是不同的变量 a, b, c. 由于字符串的内容是相同的, 所以比较的结果也是完全相同的. 对比SimpleObject的实例, smp1和smp2的值虽然也是相同的,但是比较的结果为false.
下面看一下运行时, 这些objects的的情况.
在运行时态, 一切皆是地址. 判断两个变量是否是相同的对象, 直观的可以从它地址是否是相同的地址来进行判断.
用dso命令打印出栈上对应的Objects. 可以看到Test String”虽然出现了3次, 但是他们都对应了一个地址0000000002473f90 . SimpleObject的对象实例出现了2次, 而且地址不一样, 分别是00000000024776700000000002477688 .
所以, 在使用String的时候, 实质上是重用了相同的String 对象. 在new一个SimpleObject的实例时候, 每一次new都会在新的地址上初始化该对象的结构. 每次都是一个新的对象.
 
 
  1. 0:000> !dso
  2. OS Thread Id: 0x3f0c (0)
  3. RSP/REG          Object           Name
  4. ......
  5. 000000000043e730 <strong>0000000002473f90</strong> System.String
  6. 000000000043e738 <strong>0000000002473f90</strong> System.String
  7. 000000000043e740 <strong>0000000002473f90</strong> System.String
  8. 000000000043e748 0000000002477670 ConsoleApplication3.SimpleObject
  9. 000000000043e750 0000000002477688 ConsoleApplication3.SimpleObject
  10. .......
  11. 0:000> !do 0000000002473f90
  12. Name: System.String
  13. MethodTable: 00007ffdb0817df0
  14. EEClass: 00007ffdb041e560
  15. Size: 48(0x30) bytes
  16. GC Generation: 0
  17. (C:\windows\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
  18. String: <strong>Test String</strong>
  19. Fields:
  20.               MT            Field           Offset                 Type VT             Attr            Value Name
  21. 00007ffdb081f060  4000096        8         System.Int32  1 instance               12 m_arrayLength
  22. 00007ffdb081f060  4000097        c         System.Int32  1 instance               11 m_stringLength
  23. 00007ffdb0819838  4000098       10          System.Char  1 instance               54 m_firstChar
  24. 00007ffdb0817df0  4000099       20        System.String  0   shared           static Empty
  25.                                  >> Domain:Value  0000000000581880:0000000002471308 <<
  26. 00007ffdb08196e8  400009a       28        System.Char[]  0   shared           static WhitespaceChars
  27.                                  >> Domain:Value  0000000000581880:0000000002471be0 <<
复制代码
 
String的驻留

CLR runtime通过维护一个表来存放字符串,该表称为拘留池,它包含程序中以编程方式声明或创建的每个唯一的字符串的一个引用。因此,具有特定值的字符串的实例在系统中只有一个。 我们看一下如何来理解这句话.
下面是示例代码 :
 
  1. 0:000> !dso
  2. Listing objects from: 0000000000435000 to 0000000000440000 from thread: 0 [3f0c]
  3. Address          Method Table    Heap Gen      Size Type
  4. …..
  5. 0000000002473fc0 00007ffdb0817df0   0  0         44 System.String <strong>a vs b :</strong>
  6. 0000000002474138 00007ffdb0817df0   0  0         52 System.String <strong>a vs b : True</strong>
  7. …..
复制代码
 
这是第一次的执行结果. 此时只执行到了SimpleString里面, 还没有从这个方法返回.
2.png

我们可以看到stack上有4个string. 分别是按照代码逻辑拼接起来的string的内容. 从这里我们就可以当我们在拼接字符串的时候, 实际上会在Heap上创建出多个String的对象, 以此来完成这个拼接动作.
  1. static void Main(string[] args)
  2. {
  3.     int i = 0;
  4.     while (true)
  5.     {
  6.         SimpleString(i++);
  7.         Console.WriteLine( i + " : Run GC.Collect()");
  8.         GC.Collect();
  9.         Console.ReadLine();
  10.     }
  11. }
  12. private static void SimpleString(int i)
  13. {
  14.     string s = "SimpleString method ";
  15.     string c = "Concat String";
  16.     Console.WriteLine(s + c);
  17.     Console.WriteLine(s + i.ToString());
  18.     Console.ReadLine();
  19. }
复制代码
 
随意用其中一个来检查它的引用情况.
从!gcroot的结果看, 这个string被两个地方引用到. 一个是当前的线程. 因为正在被当前线程使用到, 所以能够看到这个非常正常.
另外一个是root在一个System.Object[]数组上. 这个数组被PINNED在了App Domain 0000000000491880 上面. 这里显示出来, String其实是驻留在一个System.Object[]上面, 而不是很多人猜测的Hashtable. 不过料想CLR 应该有一套机制可以从这个数组中快速的获取正确的String. 不过这点不在本篇的讨论范围之内.
 
  1. 0:000> !dso
  2. Listing objects from: 0000000000386000 to 0000000000390000 from thread: 0 [3f50]
  3. …..
  4. 0000000002a93f70 00007ffdb0817df0   0  0         66 System.String <strong>SimpleString method</strong>
  5. 0000000002a93fb8 00007ffdb0817df0   0  0         52 System.String <strong>Concat String
  6. </strong>0000000002a93ff0 00007ffdb0817df0   0  0         92 System.String <strong>SimpleString method Concat String</strong>
  7. 0000000002a97a90 00007ffdb0817df0   0  0         28 System.String <strong>0</strong>
  8. 0000000002a97ab0 00007ffdb0817df0   0  0         68 System.String <strong>SimpleString method 0</strong>
  9. ……
复制代码
 
我们可以检查一下这个System.Object[]里面都有什么.
从这个数组里面可以看到代码中显示声明的的字符串. 第一个元素是一个空值, 这个里面保留的是我们最常用的String.Empty的实例. 第二个元素是”Run GC.Collect()”. 这个在code的里面的main函数中. 当前还没有被执行到, 但是已经被JITed到了该数组中. 其他两个被显示定义的字符串也能够在这个数组中被找到. 另外可以确认的是, 拼接出来的字符串, 临时生成的字符串都没有在这里出现. 然而, 通过拼接出来的String并不在这个数组里面. 虽然拼接出来的String同样分配到了heap上面, 但是不会被收纳到数组中.
  1. 0:000> !gcroot 0000000002a93f70
  2. Note: Roots found on stacks may be false positives. Run "!help gcroot" for
  3. more info.
  4. Scan Thread 0 OSTHread 81a0
  5. <strong>RSP:b9e9b8</strong>:Root:0000000002a93f70(System.String)
  6. Scan Thread 2 OSTHread 7370
  7. DOMAIN(0000000000C51880):HANDLE(Pinned):217e8:Root:<strong>0000000012a93030(System.Object[])-></strong>
  8. 0000000002a93f70(System.String)
复制代码
 
 
所以经过上面的观察, 可以得出的结论是驻留的String生命周期非常长. 那么, 在什么时候他才会被回收?
从上面gcroot的结果, 可以看到主流数组是被PINNED住. 而引用这个数组的App Domain 0000000000C51880.
用!dumpdomain -stat的命令将所有的app domain信息打印出来. 可以看到这个App Domain是我们代码运行的Domain (ConsoleApplication3.exe). 这个驻留数组是由CLR 来维护, 并且与当前的App Domain联系到一起. 所以, 理论上这些驻留数组的生命周期跟这个App Domain是一致的.
 
  1. 0:000> !dumparray -details 0000000012a93030
  2. Name: System.Object[]
  3. MethodTable: 00007ffdb0805be0
  4. EEClass: 00007ffdb041eb88
  5. Size: 1056(0x420) bytes
  6. Array: Rank 1, Number of elements 128, Type CLASS
  7. Element Methodtable: 00007ffdb08176e0
  8. [0] 0000000002a91308
  9.     Name: System.String
  10.     MethodTable: 00007ffdb0817df0
  11.     EEClass: 00007ffdb041e560
  12.     Size: 26(0x1a) bytes
  13.      (C:\windows\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
  14.     String:         
  15.     Fields:
  16.                   MT    Field   Offset                 Type VT     Attr            Value Name
  17.     00007ffdb081f060  4000096        8         System.Int32  1 instance                1 m_arrayLength
  18.     00007ffdb081f060  4000097        c         System.Int32  1 instance                0 m_stringLength
  19.     00007ffdb0819838  4000098       10          System.Char  1 instance                0 m_firstChar
  20.     00007ffdb0817df0  4000099       20        System.String  0   shared           static Empty
  21.                                  >> Domain:Value  0000000000c51880:0000000002a91308 <<
  22.     00007ffdb08196e8  400009a       28        System.Char[]  0   shared           static WhitespaceChars
  23.                                  >> Domain:Value  0000000000c51880:0000000002a91be0 <<
  24. [1] 0000000002a93f30
  25.     Name: System.String
  26.     MethodTable: 00007ffdb0817df0
  27.     EEClass: 00007ffdb041e560
  28.     Size: 64(0x40) bytes
  29.      (C:\windows\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
  30.     String:      : <strong>Run GC.Collect()</strong>   
  31.     Fields:
  32.                   MT    Field   Offset                 Type VT     Attr            Value Name
  33.     00007ffdb081f060  4000096        8         System.Int32  1 instance               20 m_arrayLength
  34.     00007ffdb081f060  4000097        c         System.Int32  1 instance               19 m_stringLength
  35.     00007ffdb0819838  4000098       10          System.Char  1 instance               20 m_firstChar
  36.     00007ffdb0817df0  4000099       20        System.String  0   shared           static Empty
  37.                                  >> Domain:Value  0000000000c51880:0000000002a91308 <<
  38.     00007ffdb08196e8  400009a       28        System.Char[]  0   shared           static WhitespaceChars
  39.                                  >> Domain:Value  0000000000c51880:0000000002a91be0 <<
  40. [2] 0000000002a93f70
  41.     Name: System.String
  42.     MethodTable: 00007ffdb0817df0
  43.     EEClass: 00007ffdb041e560
  44.     Size: 66(0x42) bytes
  45.      (C:\windows\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
  46.     String:     <strong>SimpleString method</strong>     
  47.     Fields:
  48.                   MT    Field   Offset                 Type VT     Attr            Value Name
  49.     00007ffdb081f060  4000096        8         System.Int32  1 instance               21 m_arrayLength
  50.     00007ffdb081f060  4000097        c         System.Int32  1 instance               20 m_stringLength
  51.     00007ffdb0819838  4000098       10          System.Char  1 instance               53 m_firstChar
  52.     00007ffdb0817df0  4000099       20        System.String  0   shared           static Empty
  53.                                  >> Domain:Value  0000000000c51880:0000000002a91308 <<
  54.     00007ffdb08196e8  400009a       28        System.Char[]  0   shared           static WhitespaceChars
  55.                                  >> Domain:Value  0000000000c51880:0000000002a91be0 <<
  56. [3] 0000000002a93fb8
  57.     Name: System.String
  58.     MethodTable: 00007ffdb0817df0
  59.     EEClass: 00007ffdb041e560
  60.     Size: 52(0x34) bytes
  61.      (C:\windows\assembly\GAC_64\mscorlib\2.0.0.0__b77a5c561934e089\mscorlib.dll)
  62.     String:     <strong>Concat String</strong>   
  63.     Fields:
  64.                   MT    Field   Offset                 Type VT     Attr            Value Name
  65.     00007ffdb081f060  4000096        8         System.Int32  1 instance               14 m_arrayLength
  66.     00007ffdb081f060  4000097        c         System.Int32  1 instance               13 m_stringLength
  67.     00007ffdb0819838  4000098       10          System.Char  1 instance               43 m_firstChar
  68.     00007ffdb0817df0  4000099       20        System.String  0   shared           static Empty
  69.                                  >> Domain:Value  0000000000c51880:0000000002a91308 <<
  70.     00007ffdb08196e8  400009a       28        System.Char[]  0   shared           static WhitespaceChars
  71.                                  >> Domain:Value  0000000000c51880:0000000002a91be0 <<
复制代码
 
写在最后面


  • String的恒定性. 字符串横定性是指一个字符串一经创建,就不可改变。那么也就是说当我们改变string值的时候,便会在托管堆上重新分配一块新的内存空间,而不会影响到原有的内存地址上所存储的值。
  • String的驻留. CLR runtime通过维护一个表来存放字符串,该表称为拘留池,它包含程序中以编程方式声明或创建的每个唯一的字符串的一个引用。因此,具有特定值的字符串的实例在系统(App Domain)中只有一个。
    直接在CODE里面声明的String会被CLR runtime维护在一个Object[]内.
    临时生成的string或者拼接出来的String不会维护在这个驻留数组中.
    驻留数组的生命周期跟它位于的App Domain一样长. 所以GC并不会影响驻留数组所引用的String, 它们不会被GC.
可以参考下面这个链接来对这两个特性加深理解.
http://blog.csdn.net/fengshi_sh/article/details/14837445
http://www.cnblogs.com/charles2008/archive/2009/04/12/1434115.html
http://www.cnblogs.com/instance/archive/2011/05/24/2056091.html

来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!

相关推荐

您需要登录后才可以回帖 登录 | 立即注册