3

I am working on an image processing project in C++. I have the following struct to represent each pixel in my image.

struct Pixel16
{
        uint16_t red;
        uint16_t green;
        uint16_t blue;
}

The size of this struct is 6 bytes. In my Image class I plan to have an array of most likely millions of these depending on the size of the image. I was wondering if I need to be worried about memory alignment? Should I align the memory to be on 8 byte boundaries. Will this increase the performance?

chasep255
  • 11,745
  • 8
  • 58
  • 115
  • Unless you need to do some tricky things with `Pixel16`, an alignment of 6 bytes would just be fine. – Lingxi Apr 19 '15 at 06:04
  • Have a look at http://stackoverflow.com/questions/381244/purpose-of-memory-alignment and http://stackoverflow.com/questions/2006216/why-is-data-structure-alignment-important-for-performance. Memory access will probably benefit from alignment, however it depends on the processor architecture. You should run benchmarks to find out if it matters for your use case. – m.s. Apr 19 '15 at 06:04
  • It depends on the compiler. Optimization will automatically align the data to 8 bytes for increased performance. – Barmak Shemirani Apr 19 '15 at 06:11
  • @BarmakShemirani: I don't believe it will alter the alignment in this case - in what compiler have you seen that? – Mats Petersson Apr 19 '15 at 06:48
  • And to the original question: Which gives better performance depends on exactly what you are doing to the Pixel16 struct - are you at any time using it as if it was a 64-bit integer? Or are you only ever reading the `red`, `green` and `blue` as 16-bit values. – Mats Petersson Apr 19 '15 at 06:50
  • @MatsPetersson: You are right. I don't know what I was thinking. I tested it with MSVC, it doesn't add pad. Oddly enough, when optimization is off, speed increases by 50% by manually adding pad. If optimization is on, adding pad has no effect. – Barmak Shemirani Apr 19 '15 at 07:53

0 Answers0