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

I read somewhere that using BOOL (typedef int) is better than using the standard bool type of type C ++, since the size of BOOL is 4 bytes (i.e., a multiple of 4), and it saves the operations of aligning variables into registers or what something like a line ...

Is there any truth to this? I assume that the compiler will stack stack frames to maintain alignment several times, even if you use bool (1 byte)?

I am by no means an expert on the basic workings of alignments, registers, etc., so I apologize in advance if this is completely wrong with me. I hope it fixes me. :)

Hooray!

+7
source share
3 answers

First of all, sizeof(bool) not necessarily 1 . This implementation is defined , giving the compiler developer the freedom to choose the size suitable for the target platform.

Also, sizeof(int) not necessarily 4 .

There are several issues that can affect performance:

  • alignment;
  • memory bandwidth;
  • The ability of the CPU to efficiently load values ​​that are narrower than a machine word.

What - if any - the difference that makes for a specific piece of code can only be established by profiling this piece of code.

+7
source

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


0) Although the byte does not have a specific size. sizeof(char) always 1 byte , but maybe 40 binary bits in fact

1) Yes, there are uint32_t and friends, but no, their definition is not necessary for real 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 different types, and it is not determined whether char signed or not. Keep this in mind when overloading functions and writing templates.

+2
source

There are three generally accepted performance-oriented practices regarding Booleans:

  • In if-statements, the order in which expressions are checked matters, and you need to be careful with them.
  • If checking a Boolean expression causes many incorrect branch predictions, then it should (if possible) be replaced with a small hack.
  • Since boolean is the smallest data type, booleans must be declared last in structures and classes, so adding does not add noticeable holes in the layout of the structure structure.

I have never heard of performance improvements when replacing a boolean with an (unsigned?) Integer.

0
source

All Articles