计算 object 的大小,使其包括其所有 children 和(大 children 链的大小)

Calculate size of object such that it include size of all its children and (grand children chain)

假设classA包含B和C的实例。B包含D、E和F,而C包含G、H和I的实例。所以在计算A的大小时,我想包括其所有及其 child 项的大小。当我使用 !dumpheap -stats 命令时,A 的大小似乎不包括其包含的所有 children、grand-children、grand-grand children。

有什么方法可以在windbg中以这种方式获取A的大小吗?

我觉得

!objsize <object address>

就是您要找的。

但是,它仅适用于单个 objects(!dumpheap -stat 总结所有 objects,但不包括在内)。如果你想为该类型的所有 objects 执行此操作,则需要 !dumpheap -short -type 和一个循环。

解决 Marc Sherman 的评论:

According to the doc !objsize gets the size of the parent and its children, it doesn't mention grand-children and beyond: "The ObjSize command includes the size of all child objects in addition to the parent."

!dumpheap不考虑children:

0:006> !dumpheap -mt 02b24dfc
 Address       MT     Size
02e92410 02b24dfc       28     
02e9242c 02b24dfc       28     
02e92474 02b24dfc       28    
[...]

但是 !objsize 会:

0:006> !objsize 02e92410
sizeof(02e92410) = 28 (0x1c) bytes (ObjSizeChildren.Object)
0:006> !objsize 02e9242c
sizeof(02e9242c) = 72 (0x48) bytes (ObjSizeChildren.Object)
0:006> !objsize 02e92474
sizeof(02e92474) = 160 (0xa0) bytes (ObjSizeChildren.Object)

使用此代码检查:

class Program
{
    static void Main()
    {
        var o1 = new Object();
        var o2 = new Object {child = new Child()};
        var o3 = new Object {child = new Child {grandChild = new GrandChild()}};
        Console.WriteLine("Debug now");
        Console.ReadLine();
        Console.Write(o1);
        Console.Write(o2);
        Console.Write(o3);
    }
}

class Object
{
    private long a;
    private long b;
    public Child child;
}

internal class Child
{
    private long a;
    private long b;
    private long c;
    private long d;
    public GrandChild grandChild;
}

internal class GrandChild
{
    private long a;
    private long b;
    private long c;
    private long d;
    private long e;
    private long f;
    private long g;
    private long h;
    private long i;
    private long j;
}