Let's say I want to get extra type-checking for working with primitives that mean different things semantically:
public struct Apple
{
readonly int value;
// Add constructor + operator overloads
}
public struct Orange
{
readonly int value;
// Add constructor + operator overloads
}
The point is we can't compare "apples to oranges", so wrapping up the actual int in a struct means we get type checking and some extra readability and documentation by code.
My question is: what is the overhead associated with doing this, both in terms of memory and speed? Since structs are value types, would variables containing these structs be 32 bits or larger? What about performance overhead of using these structs instead of primitives - is there a large overhead for the operator overloads?
Any other advice on the wisdom of doing this?
In memory there is no overhead using a struct which you can verify using Marshal.SizeOf()
:
struct testStruct
{
public readonly int value;
}
..
int size = Marshal.SizeOf(typeof(testStruct)); //returns 4
This also is the same as returned by sizeof(testStruct)
:
unsafe
{
int size = sizeof(testStruct); //returns 4
}
According to MSDN the difference between the two sizing methods is:
Although you can use the Marshal.SizeOf method, the value returned by this method is not always the same as the value returned by sizeof. Marshal.SizeOf returns the size after the type has been marshaled, whereas sizeof returns the size as it has been allocated by the common language runtime, including any padding.
I'll probably get shunned for this, but you could do:
using Apple = System.Int32;
using Orange = System.Int32;
You won't be able to use it across files. And technically you can still compare apples to oranges.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With