Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Memory taken from a c# object

Tags:

.net

oop

memory

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.

like image 900
George Statis Avatar asked Aug 13 '09 16:08

George Statis


2 Answers

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

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
{
}

Test:

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 overhead etc explains why the number isn't always an exact integer - hence why I do the division in floating point.)

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

like image 89
Jon Skeet Avatar answered Oct 14 '22 02:10

Jon Skeet


An object has two references/pointers additional to it's own data.

So, on a 32 bit system the object would take 8 bytes, on a 64 bit system it would take 16 bytes.

Correction:
As Jon stated, the minimum size for an object is 12 bytes. The information that I found so far says that the GC requires this.

like image 31
Guffa Avatar answered Oct 14 '22 04:10

Guffa