Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a performance penalty access an array of 32-bit integers in x86-64?

Tags:

c++

c

x86-64

Sorry if the question sounds stupid. I'm only vaguely cognizant of the issue of data alignment and have never done any 64-bit programming. I'm working on some 32-bit x86 code right now. It frequently accesses an array of int. Sometimes one 32-bit integer is read. Sometimes two or more are read. At some point I'd like to make the code 64-bit. What I'm not sure is whether I should declare this int array as int or long int. I would rather keep the width of the integer the same, so I don't have to worry about differences. I'm sort of worried though that reading/writing off an address that isn't aligned to the natural word might be slow.

like image 695
cleong Avatar asked Sep 16 '12 20:09

cleong


1 Answers

Misalignment penalties only occur when the load or store crosses an alignment boundary. The boundary is usually the smaller of:

  • The natural word-size of the hardware. (32-bits or 64-bit*)
  • The size of the data-type.

If you're loading a 4-byte word on a 64-bit (8-byte) architecture. It does not need to be 8-byte aligned. It only needs to be 4-byte aligned.

Likewise, if you're loading a 1-byte char on any machine, it doesn't need to be aligned at all.

*Note that SIMD vectors can imply a larger natural word-size. For example, 16-byte SSE still requires 16-byte alignment on both x86 and x64. (barring explicit misaligned loads/stores)


So in short, no you don't have to worry about data-alignment. The language and the compiler tries pretty hard to prevent you from having to worry about it.

So just stick with whatever datatype makes the most sense for you.

like image 129
Mysticial Avatar answered Sep 27 '22 16:09

Mysticial