!objsize
计算实例的大小,包括其所有引用的对象,因此如果您有任何对象共享对其他对象的引用,则这些对象的大小将被计算多次。最常见的来源可能是字符串,因为文字字符串是内部的,因此使用相同的文字文本在对象之间共享。但是,您也可能有引用相同对象的集合。在任何情况下,总和都是不正确的,除非计数的对象根本不共享任何引用。
考虑这个例子
class SomeType {
private readonly string Text;
public SomeType(string text) {
Text = text;
}
}
和这段代码
var st1 = new SomeType("this is a long string that will be stored only once due to interning");
var st2 = new SomeType("this is a long string that will be stored only once due to interning");
在 WinDbg 中
0:006> !dumpheap -type Some
Address MT Size
00ceb44c 00b738a8 12
00ceb458 00b738a8 12
0:006> !objsize 00ceb44c
sizeof(00ceb44c) = 164 ( 0xa4) bytes (TestApp.SomeType)
0:006> !objsize 00ceb458
sizeof(00ceb458) = 164 ( 0xa4) bytes (TestApp.SomeType)
0:006> !DumpObj 00ceb44c
Name: TestApp.SomeType
MethodTable: 00b738a8
EEClass: 00b714bc
Size: 12(0xc) bytes
File: c:\dev2010\FSharpLib\TestApp\bin\Release\TestApp.exe
Fields:
MT Field Offset Type VT Attr Value Name
79b9d2b8 4000001 4 System.String 0 instance 00ceb390 Text
0:006> !DumpObj 00ceb458
Name: TestApp.SomeType
MethodTable: 00b738a8
EEClass: 00b714bc
Size: 12(0xc) bytes
File: c:\dev2010\FSharpLib\TestApp\bin\Release\TestApp.exe
Fields:
MT Field Offset Type VT Attr Value Name
79b9d2b8 4000001 4 System.String 0 instance 00ceb390 Text
正如您从 的输出中看到的那样!dumpobj
,它们都共享相同的引用,因此如果您将!objsize
上面报告的大小相加,则该字符串被计算两次。