Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Overhead of using structs as wrappers for primitives for type-checking?

Tags:

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?

like image 650
Mike Avatar asked May 30 '11 23:05

Mike


2 Answers

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.

like image 69
BrokenGlass Avatar answered Oct 09 '22 12:10

BrokenGlass


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.

like image 21
Marlon Avatar answered Oct 09 '22 10:10

Marlon