Structuring overhead of C # primitive type aliases?

I noticed that primitive types in C # are really just implemented as aliases for structures defined in a namespace System

, for example. ulong

is an alias System.UInt64

that has a type struct

. Is there any additional additional overhead for primitive types in C # arising from this? Say, does it really ulong

consume only 8 bytes of memory?

In the spirit this is to check for memory overhead:

using System;

class Program
    static void Main()
        long beforeAlloc = GC.GetTotalMemory(false);
        ulong[] myArray = new ulong[System.Int32.MaxValue];
        myArray[0] = 1;
        long afterAlloc = GC.GetTotalMemory(false);

        Console.WriteLine(((afterAlloc - beforeAlloc) / System.Int32.MaxValue).ToString());


But the documentation points out that the method GC.GetTotalMemory()

only gets the number of bytes currently thought to be allocated, so isn't there an easy way to find out without more complex memory profiling?


source to share

2 answers

There is no overhead from the structure itself. However, the runtime is free to host any composite types as an alignment optimization.

For details on how arrays are handled at runtime, see this question .



Primitive types are flattened by the compiler. In the resulting code, it makes no difference if you use int

or System.Int32

. In your example, System.UInt64

and ulong

are two structures; they both inherit from System.ValueType. This is because they are actually the same type.

The compiler will be slightly faster, however, if you use keywords. When you use, for example, the Int32

compiler resolves the type name from all other types in scope, looking at the namespace and directives using

to determine that the type is not some other type Int32

that someone else wrote. This does not happen with aliases.

If you can find an example where this difference is truly measurable, I would be very surprised!



All Articles