9

In my code, I have the following struct:

struct foo {
 int a;
 int b;
};

In b, only values between 0 and 100 are stored. So in general, I could replace it by a char. But than the size of the struct is the same due to padding effects. As my code contains vectors and sets of these structure with several million entries, it would bring the memory usage down by more than one third if I could circumvent padding in some way. Is there any possibility to do this, e.g. some other (boost) data container which behaves in the same way?

Edit: I use both, the GNU and the Intel compiler on Linux systems:

11
  • 3
    You need a struct pack-ing. Depends on your compiler, you may use (probably pragma pack) to tell your compiler, not to add padding. Commented Nov 1, 2012 at 14:22
  • 2
    @Kiril Why did you not add this as an answer? Commented Nov 1, 2012 at 14:26
  • 1
    Perhaps you could split your struct in two. Commented Nov 1, 2012 at 14:33
  • 2
    Do you really need to pack it? Most processors are more efficient with the native size (integer) than a smaller size. Also, there may be extra processing time required to handle the smaller sizes; check your assembly code. Is the packing going to save you huge amounts of memory space? Commented Nov 1, 2012 at 15:04
  • 3
    @ThomasMatthews: I made some benchmarks: The part of my code, which works on this data is around 10% slower with the packed data. But this part takes just 1% of the overall runtime, so the extra slowdown does not really matter. But, the data is responsible for more than 30% of the code's memory usage. Commented Nov 2, 2012 at 6:58

2 Answers 2

7

Moving my comment as an answer, as the community advised :)

This is compiler dependent. What you need is to use struct packing.

For Visual Studio, you need #pragma pack and for gcc, you need to use an attribute packed.

For more information, see C++ struct alignment question

Hope that helps, sorry I can't really test it right now, but that's what you need

Sign up to request clarification or add additional context in comments.

Comments

3

Short of using special #pragmas to control the structure padding/alignment, you could split a and b and store them in separate vectors, and "match" them by index.

As for sets, even if you could easily split the structure to its constituent parts (which you probably can't from the purely logical perspective - sets don't have indexes), you'd still pay for dynamic memory management alignment which would likely erase any advantage you might have gained with that.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.