Reputation: 2567
I noticed that the primitive types in C# are really just implemented as aliases to structs defined in the System
namespace, e.g. ulong
is an alias to the System.UInt64
, which is of struct
type. Is there any additional space-time overhead to the primitive types in C# arising from this? Say, does ulong
really consume only 8 bytes of memory?
In spirit, this should test the 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 specifies that GC.GetTotalMemory()
method only retrieves the number of bytes currently thought to be allocated, so is there no easy way of finding out without a more sophisticated memory profiler?
Upvotes: 3
Views: 669
Reputation: 43046
The primitive types are aliased by the compiler. There is no difference in the resulting code whether you use int
or System.Int32
. In your example, System.UInt64
and ulong
are both structs; they both inherit from System.ValueType. This is because, in fact, they are the same type.
The compiler will be marginally quicker, however, if you use the keywords. When you use, for example, Int32
, the compiler resolves the type name from among all other types in scope, with attention to the namespace and using
directives, to determine that the type isn't some other Int32
type that someone else wrote. This doesn't happen with the aliases.
If you can find an example where this difference is actually measurable, I'd be very surprised!
Upvotes: 1
Reputation: 116411
There is no overhead from a struct itself. However, the runtime is free to pad any compound types as an alignment optimization.
For details about how arrays are handled at run-time please see this question.
Upvotes: 3