On order of data members only

Does the order of data members only in class (so many) matter
and is it quite influential in accesses efficiency ?

if yes or no, how is each logical reasons ?
Last edited on
The order of data members matters for a class constructor as the order of initialization using member initialization list is the order the variables are defined in the class and not the order the initialization is specified in the list.
the order also lets you cast the identical parts, if you need to do raw byte level manipulation of that sort.

so if you have
1
2
3
4
5
6
7
8
9
10
11
12
13
14
struct one
{
   int x; 
   int y;
   double d;
};
and
struct two
{
   int x; 
   int y;
   string s;
};

you can cast one to the other and read x and y safely, but nothing past the first difference. C++ has better ways of doing this kind of thing, but it is useful on occasion in C or very low level code or if using a simple design.
and is quite influential in accesses efficiency
It will be stored in memory the order that it is declared. This will sometimes mean that a different ordering can be stored more compactly, depending on alignment necessities.

The way the variables are laid out can affect cache efficiency. Most consumer machines have around a 64-byte cache line. So if, for example, you have an array of objects, and each object has a thousand different member variables, but you have a loop that only needs to operate on one of those members in the array, then you will get a cache miss every single time you access the next element in the array.

But if you had a dedicated array that only had that one particular member variable packed into it, and let's say that member variable is 4 bytes large, that means you can go through 64/4 = 16 elements at a time before hitting the next cache miss, which can be a notable performance increase (as always, MEASURE, don't assume).
Last edited on
"alignment"

When I did look at SSE/SSE2 intrinsics (long time ago, before C++ had support for specified alignment), proper alignment was crucial for vectorized operations.
Topic archived. No new replies allowed.