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;
}
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.
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.
– UnitraxxWhere 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@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).
– AndyMartin458It 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?"
– AndyMartin458Did anyone ever try out anything that confirmed what @Tarlius said?
– AndyMartin458