In the .NET struct design guidelines, it gives the maximum sensible size of a struct as 16 bytes. How do you determine how large your struct is, and is it affected by the architecture your program is running on? Is this value 32-bit only, or for both archs?
In 32 bit processor, it can access 4 bytes at a time which means word size is 4 bytes. Similarly in a 64 bit processor, it can access 8 bytes at a time which means word size is 8 bytes. Structure padding is used to save number of CPU cycles.
In the 64-bit build mode the structure MyStruct will take 24 bytes. It is clear. First there is one byte for m_bool and 7 vacant bytes for the purpose of alignment because a pointer takes 8 bytes and must be aligned on an 8-byte boundary.
One bit in the register can reference an individual byte in memory, so a 32-bit system can address a maximum of 4 GB (4,294,967,296 bytes) of RAM. The actual limit is often less than around 3.5 GB since part of the register is used to store other temporary values besides memory addresses.
Therefore, we can say that a 32-bit processor is capable of accessing 4 bytes at a time, whereas a 64-bit processor is capable of accessing 8 bytes at a time.
It's not a hard-and-fast value - it's just a guideline, a rule of thumb. Depending on the exact situation, 24 or even 32 bytes could still be perfectly justifiable - but if your struct gets that large you should really be asking yourself whether it's appropriate as a struct in the first place. It may be - in which case taking the hit of copying those 32 bytes around any time you perform an assignment or pass an argument into a method (etc) may be the right thing to do; in other cases you should really be using a class.
As for how you determine how big your struct is - usually it's fairly obvious, because usually a value type only contains other value types. If your struct contains references (or an IntPtr
/UIntPtr
), that's more of a problem - but that's pretty rare. (As Mehrdad points out, there's also the issue of padding for the sake of alignment.)
Then again, I find it extremely rare that I want to write my own struct anyway. What's your situation?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With