-1

Say I have a simple C++ class that contains a variety of types with different sizes. To my understanding, types with identical sizes should be grouped together to maximize memory alignment. Assuming my goal is to maximize memory efficiency

What would be the best way of ordering types of differing sizes? In the example below, assume HeavyClass is a large object. Am I correct in placing large objects at the end?

class MyClass {
  int d_someInt;
  int d_anotherInt;
  long d_someLong;
  HeavyClass d_heavyClass;
};

The usual things like cache locality, readability apply but all other being equal, I want to maximize alignment.

Howard Grimberg
  • 2,128
  • 2
  • 16
  • 28
  • 4
    Unless you dealing with super-low-latency, prefer human readability over packing efficiency - i.e. put fields which are related to each other close to each other. – SergeyA May 21 '19 at 16:00
  • 4
    That all depends. Usually larger objects are placed first, since they will have the most strict alignment needs. However, in some cases it makes sense to place frequently accessed members first (to allow smaller constant offsets when accessing them), thus reducing code size. – 1201ProgramAlarm May 21 '19 at 16:00
  • When alignment is not an issue, I like to sort the data members by member name. This helps when trying to find data members. – Thomas Matthews May 21 '19 at 16:13
  • 2
    The best ordering is achieved by placing the largest objects first and the smallest objects last. **BUT** that is a super micro optimization that you should not be worrying about (with specific very clearly defined exceptions). If you are asking this question you probably don't know enough to do this properly so don;'t worry about it and let the compiler worry about micro optimizations (it is usually better than normal humans). – Martin York May 21 '19 at 17:46
  • @MartinYork That's probably the right answer in practice – Howard Grimberg May 21 '19 at 20:03

1 Answers1

1

Maximizing alignment is only one potential goal, you may also wish to group based on usage (members that will be used together are close together in the class definition). Having members that will be used together near each other can also help performance due to cache hits (that is the CPU won't have to fetch from main memory as often). Maximizing alignment is most likely to be a desirable strategy when you will have arrays of your type, that way you won't have as much unused padding).

SoronelHaetir
  • 14,104
  • 1
  • 12
  • 23