内存从C#对象获取的 [英] Memory taken from a c# object

查看:142
本文介绍了内存从C#对象获取的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道有多少内存的对象,它继承了对象,并没有字段/属性走?我猜方法没有。对 ?我说的是.NET对象。

I was wondering how much memory does an object that inherits from "object" and has no fields/properties take ? And I guess methods don't. Right ? I am talking for .net objects.

推荐答案

好了,因为这两个安德鲁和Guffa给了答案,我认为是错误的...

Okay, as both Andrew and Guffa have given answers which I believe to be wrong...

还有一个8字节的开销为所有对象(在x86),但还有的的12字节的最小尺寸。我不知道为什么...但它意味着,这两个类的两个的需要每个实例12个字节:

There's an 8 byte overhead for all objects (on x86), but there's also a minimum size of 12 bytes. I don't know why... but it means that these two classes both take 12 bytes per instance:

public class OneField
{
    private int field;
}

public class NoFields
{
}

测试:

using System;

public class OneField
{
    private int field;
}

public class NoFields {}

public class Test
{
    static void Main(string[] args)
    {
        int size = int.Parse(args[0]);
        switch (args[1])
        {
            case "NoFields":
                TestNoFields(size);
                break;
            case "OneField":
                TestOneField(size);
                break;
        }
    }

    static void TestNoFields(int size)
    {
        NoFields[] array = new NoFields[size];
        long start = GC.GetTotalMemory(true);
        for (int i=0; i < size; i++)
        {
            array[i] = new NoFields();
        }
        long end = GC.GetTotalMemory(true);
        GC.KeepAlive(array);
        Console.WriteLine("Size per instance: {0}",
                          (end-start) / (double)size);
    }

    static void TestOneField(int size)
    {
        OneField[] array = new OneField[size];
        long start = GC.GetTotalMemory(true);
        for (int i=0; i < size; i++)
        {
            array[i] = new OneField();
        }
        long end = GC.GetTotalMemory(true);
        GC.KeepAlive(array);
        Console.WriteLine("Size per instance: {0}",
                          (end-start) / (double)size);
    }
}

这是丑陋的,因为我故意没有去任何泛型类型或其他任何可能导致的问题。一些测试运行:

This is ugly because I've deliberately not gone for any generic types or anything else that could cause issues. A few test runs:

>test 1000000 NoFields
Size per instance: 12.000024
>test 1000000 OneField
Size per instance: 12.000024
>test 1000 NoFields
Size per instance: 12
>test 1000 OneField
Size per instance: 12

(JITting开销等解释了为什么一些并不总是一个准确的整数 - 因此为什么我做除法的浮点数)

(JITting overhead etc explains why the number isn't always an exact integer - hence why I do the division in floating point.)

测试与一个额外的int字段显示使用率上升到16,这证明它实际上是做一些合理的:)

Testing with an extra int field shows the usage going up to 16, which proves it is actually doing something sensible :)

这篇关于内存从C#对象获取的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆