Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the optimal order of members in a class?

If I have the following class:

class Example
{
  bool m_b1;
  SomeClass m_sc;  
  bool m_b2;
  char * m_name;
  bool m_b3;
  int m_i1;
  SomeClass * m_sc;
  int m_i2;
};

What is the optimal order of members? As far as I know, the order of declaration of members equals the order of members in memory, when creating an instance of this class.

  • Should I sort the members so that equal types are together?
  • Do all pointers count as the same type?
  • Does rearrangement have an effect on the size of the object? Does 4 or 8 byte alignment apply here?
  • How can I see the effects of the above? Does sizeof show the memory used by an object including empty space for alignment?
  • Is it better at the end of the day to sort the members so that their meaning and context is easier to understand?
like image 904
Fabian Avatar asked Feb 04 '16 09:02

Fabian


3 Answers

As a rule of thumb you should order by size, greater to smaller. This will create the minimum padding of the structure, thus minimizing the structure size. This matters most if objects of the structure are used in a contiguous allocated memory, e.g. vector and helps a lot with cache (more objects fit in the same cache line).

Another surprising optimization demonstrated by Andrei Alexandrescu (I think was in one of CppCon) is that he brought the most accessed member first. This is faster because the offset is zero. Of course he was talking about micro-optimization, after benchmarking the hell out of the application and caring for every little strop of performance.

like image 125
bolov Avatar answered Oct 11 '22 04:10

bolov


The order is important when a member variable depends on another member variable when using initializer lists:

Imagine a class with two variable where the constructor of the second variable (varC) needs the first (varB)

class A
{
    B varB;
    C varC;

    A()
    : varC(varB)
    {
    }
};

The order decides in which steps the constructors are executed, so changing the order of varB and varC will pass a uninitialized object of varB to varC.

Of course, style and readability are also important.

like image 25
Thomas Fannes Avatar answered Oct 11 '22 04:10

Thomas Fannes


Should I sort the members so that equal types are together?

If it increases readability, Yes!

Do all pointers count as the same type?

Yes, all pointers should take either 32bit or 64bit or whatever the system defines.

Does rearrangement have an effect on the size of the object? Does 4 or 8 byte alignment apply here?

This is possible, because of alignment. Live example.

Is it better at the end of the day to sort the members so that their meaning and context is easier to understand?

If it increases meaning, readability and maintainability, YES.

like image 3
Mehrdad Avatar answered Oct 11 '22 04:10

Mehrdad