开发者

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

Let's say I wan开发者_如何学Ct 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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜