My question is why doesnt the Visual Studio 2012 compiler automatically reorder struct members for best memory utilization? The compiler seems to store the members in exactly the order they are declared in the struct definition, with some empty padding as required for member alignment. It seems like reordering would be a more desirable way to align the members than padding, whenever possible. Is there a reason it must be stored in memory in declaration order?
Pertinent details follow;
I have a struct which represents a single element in what will be a large array. The element has a number of members, some 32 bit, some 64 bit. I have default struct member alignment tuned on for best performance.
I was exploring memory in debug mode and found that a signficant percentage of the memory was being wasted. I tracked the problem to how the stuct members were aligned in memory. I know that 32 bit members must be aligned on DWORD boundaries for best performance and it would appear that evidently 64 bit members must be aligned on QWORD boundaries (I would have thought DWORD boundaries would have been adequate)
I was able to fix the problem by changing the order in which I listed the members in the struct definition. I made sure to put 2 32 bit members consequtively whenever possible so that no padding is required to start the next 64 bit member on a QWORD boundary.