I'm confused about what the size of an enum in C# is supposed to be. There appears to be a difference reported by YourKit depending on whether I use .Net 2.0/3.0/3.5 vs .Net 4.0.
Basically I have this:
>>>
public enum TestEnum : int
{
Zero = 0,
One = 1,
Two = 2,
Three = 3
}
<<<
And then some class that has some of these fields:
>>>
class Thing
{
TestEnum val_;
TestEnum val2;
}
<<<
And a function that allocates and saves a reference
>>>
static void Test()
{
Thing t = new Thing();
t.val = TestEnum.Three;
lastThing = t;
}
private static Thing lastThing;
<<<
And then some code like this:
>>>
Console.WriteLine(sizeof(TestEnum)); // This prints "4"
for (int i = 0; i < 1014; ++i)
{
Test();
}
// Just to hang around so we can do a profiler dump
Console.ReadLine();
<<<
The YourKit Object Explorer shows the following:
If I compile (Visual Studio 2010) with the
Target Framework: .Net Framework 4 Client Profile
>>>
Name Retained Size Shallow Size
CSharpFun.TestEnum = Three 4 4
value__ = Int32 3 0x00000003 4
<<<
But if I compile with the
Target Framework: .Net Framework 3.5 Client Profile
>>>
Name Retained Size Shallow Size
CSharpFun.TestEnum = Three 12 12
value__ = Int32 3 0x00000003 4
<<<
If I run this program (.Net 3.5 version) in WinDbg and do this:
>>>
!dumpheap -type Thing
<<<
Then I get results like this:
>>>
02690604 001934a8 16
02690614 001934a8 16
total 1014 objects
Statistics:
MT Count TotalSize Class Name
001934a8 1014 16224 CSharpFun.Program+Thing
Total 1014 objects
<<<
So, my Thing class has:
8 bytes .Net object overhead
4 byte enum
4 byte enum
Seems like YourKit is using the wrong size in the 3.5 (probably all 2.0/3.0) case.
Jeremy