C++ Memory alignment - should we care?
This is more complicated than it may seem.
By ordering your members according to alignment needs you'll save some padding bytes and the total size will be smaller. This may be important to you if memory is tight or if this means the type can fit in a single cache line rather than two or three.
On the other hand; if you often access members that used to be close together so they would often be pulled into cache together by the CPUs prefetcher before, but now won't after reorganizing the class. Then you could be saving memory but sacrificing runtime performance.
Performance here may also vary greatly across different CPUs and different compilers/compiler options.
You'll need to run some benchmarks in your actual environment to see what performs the best for you.
Also keep in mind that reshuffling your member variables changes the order of initialization, which can be important if members depend on each other (foo initializes bar, so foo needs to be initialized first, etc).
Yes. In theory, the alignment of your data structures matters if you are concerned about the performance. It is good programming practice as well.
Most of the time, the alignment of your data structure is set based on the widest member of the 'struct'. Normally, your compiler takes care of it for you. The behaviour, however, can be different for C++ and C when in comes to inserting leading padding.
You can use the offsetof
macro to evaluate the distance of a given struct
member in size_t
. This is ANSI C, though.
#include <stdio.h>
#include <stddef.h>
typedef struct Test_t {
char *p;
char c;
int i;
long l;
} Test;
int main(){
printf("offsetof(Test,p) = %zu\n", offsetof(Test,p));
printf("offsetof(Test,c) = %zu\n", offsetof(Test,c));
printf("offsetof(Test,i) = %zu\n", offsetof(Test,i));
printf("offsetof(Test,l) = %zu\n", offsetof(Test,l));
return 0;
}
This will print
offsetof(Test,p) = 0
offsetof(Test,c) = 8
offsetof(Test,i) = 12
offsetof(Test,l) = 16