Search code examples
javac#optimizationstructmemory-optimization

C# struct memory optimization?


I had a job interview for probation(? I'm not sure if that's the word) and interviewer asked me to tell him what are the differences between structure and class.

So I told him everything I knew and everything that I've read on msdn.

And the guy said "not enough", I didn't have a clue. So he said:

The struct are optimized, so if there is and integer and float, which have some bites identical, then it will save this space, so struct with int=0 and float=0 is half the size of int=int.MAX, float=float.MIN.

Okay. So I was like - didn't hear about that.

But then, after the interview I was thinking about it and it doesn't really make sense to me. It would mean, that the struct size differs while we're changing the value of some variable in it. And it can't really be in the same place in memory, what if there is a collision while expanding. And we would have to write somewhere what bits we're skiping, not sure if it would give any optimization.

Also, he asked me at the begging what is the difference in struct and class in Java. To which I have answered, that there is no struct in Java and he said "Not for programmers, but Numeric types are structures" I was kind of like WTF.

Basically the question is:

Did this guy know something, which is very hard to get to know (I mean, I was looking for it on the web, can't find a thing)

or maybe he doesn't know anything about his job and tries to look cool at the job interviews.


Solution

  • The guy seems to be confused about the StructLayoutAttribute that can be applied to C# structs. It allows you to specify how the struct's memory is laid out, and you can, in fact, create a struct that has fields of varying types that all start at the same memory address. The part he seems to have missed is that you're going to only use one of those fields at a time. MSDN has more info here. Look at the example struct TestUnion toward the bottom of the page. It contains four fields, all with FieldOffset(0). If you run it, you can set an integer value to the i field and then check the d field and see that it has chnaged.