简体   繁体   中英

In practice, will a C# struct with a single member be as efficient as using that single member outside of a struct?

I am developing a library which internally passes around integer values which are not really integers but convenient containers of bits.

For my own sanity, I'd prefer to instead do this...

internal struct MyStruct
{
    private readonly int myInt;
    /* Constructor and get accessors. */
}

... and pass around MyStruct values instead of int values. This way I can use my nice get accessors and the compiler will prevent me from using the wrong type.

Can I be reasonably sure that I've not introduced an inefficiency by doing this? It feels like once the compiler has done its thing, all uses of MyStruct should boil down to a simple int, taking up a single register just as an int would.

My experience tells me that single member structs do indeed compile down the way I would want them to, but I'm having trouble pinning that down to anything more than a gut feeling.

This is only half an answer: I believe you are correct in that the struct member is simply part of the struct itself and therefore gets passed around the same way as an int would, as the struct and the int have the same size (though I can't find a definitive answer from the language spec).

However, there is a surprising performance penalty to be paid for making your member readonly. See John Skeet's explanation at https://codeblog.jonskeet.uk/2014/07/16/micro-optimization-the-surprising-inefficiency-of-readonly-fields/

I would therefore make your member non-readonly, and just not create any mutators for it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM