Does variable order affect class size due to byte alignment in C#/Unity

I’ve studied recently that in C++ the order of your variables can ultimately affect the memory of your class due to byte alignment. Is the same true for our classes in C#?

class memInefficient{
    int i1;  //It's safer to put the 2 bool vars at the end?
    bool b1;
    bool b2;
    int i2;
}

Although it probably happens in C# too, as with C++ it's not at all a problem. If you really care about the small portion of memory that gets "wasted" just try to group all the variables of the same type together, minimilazing those gaps.

–

Where did you read this? I've never heard of anything of the sort :s As far as I'm aware, bools are just glorified ints. Either way, if this was this case, I would be absolutely shocked if the compiler didn't do this for you.

–

@Tarlius It's definitely true in C++ in Visual Studio 2010. You can try by making a class and then checking it's size with sizeof(myClass).

–

It was more of a question of "does it happen" as opposed to "does it matter." I suppose I'll just have to check and see if it is affected by the alignment. I suppose my question was more of "Does Unity have any suggestions for variable ordering?"

–

Did anyone ever try out anything that confirmed what @Tarlius said?

–

1 Answer

1

I created a few structs with different organization of the variables. It appears to me that the arrangement does not affect the struct when I used Marshal.SizeOf(). It really is a letdown that I can’t use sizeof on a class. It is nearly certain that C# takes care of the variable memory alignment for you.