Karl Hansson
Karl Hansson

Reputation: 237

C++ BOOL (typedef int) vs bool for performance

I read somewhere that using BOOL (typedef int) is better than using the standard c++ type bool because the size of BOOL is 4 bytes (i.e. a multiple of 4) and it saves alignment operations of variables into registers or something along those lines...

Is there any truth to this? I imagine that the compiler would pad the stack frames in order to keep alignments of multiple of 4s even if you use bool (1 byte)?

I'm by no means an expert on the underlying workings of alignments, registers, etc so I apologize in advance if I've got this completely wrong. I hope to be corrected. :)

Cheers!

Upvotes: 8

Views: 10901

Answers (3)

Anton Pegushin
Anton Pegushin

Reputation: 470

There are three commonly accepted performance-driven practices in regards to booleans:

  1. In if-statements order of checking the expressions matters and one needs to be careful about them.
  2. If a check of a boolean expression causes a lot of branch mispredictions, then it should (if possible) be substituted with a bit twiddling hack.
  3. Since boolean is a smallest data type, boolean variables should be declared last in structures and classes, so that padding does not add noticeable holes in the structure memory layout.

I've never heard about any performance gain from substituting a boolean with (unsigned?) integer however.

Upvotes: 0

Sebastian Mach
Sebastian Mach

Reputation: 39109

The only guaranteed size you can get in C++ is with char, unsigned char, and signed char 2), which are always exactly one byte and defined for every platform.0)1)


0) Though a byte does not have a defined size. sizeof(char) is always 1 byte, but might be 40 binary bits in fact

1) Yes, there is uint32_t and friends, but no, their definition is optional for actual C++ implementations. Use them, but you may get compile time errors if they are not available (compile time errors are always good)

2) char, unsigned char, and signed char are distinct types and it is not defined whether char is signed or not. Keep this in mind when overloading functions and writing templates.

Upvotes: 2

NPE
NPE

Reputation: 500953

First of all, sizeof(bool) is not necessarily 1. It is implementation-defined, giving the compiler writer freedom to choose a size that's suitable for the target platform.

Also, sizeof(int) is not necessarily 4.

There are multiple issues that could affect performance:

  • alignment;
  • memory bandwidth;
  • CPU's ability to efficiently load values that are narrower than the machine word.

What -- if any -- difference that makes to a particular piece of code can only be established by profiling that piece of code.

Upvotes: 9

Related Questions