Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 464
Karl Hansson Avatar asked May 09 '12 08:05

Karl Hansson


People also ask

Which is faster bool or int?

Surprisingly, g(bool) generates more asm instructions! Does it mean that if(bool) is little slower than if(int) ? I used to think bool is especially designed to be used in conditional statement such as if , so I was expecting g(bool) to generate less asm instructions, thereby making g(bool) more efficient and fast.

Should I use Stdbool?

So do indeed use stdbool. h if you aren't bound to some existing home-brewed bool . It will be the standard type, with all the benefits that type brings in. Answer which actually gives the true reason: backward compatibility with already written code.

Is bool the same as int?

Treating integers as boolean values C++ does not really have a boolean type; bool is the same as int. Whenever an integer value is tested to see whether it is true of false, 0 is considered to be false and all other integers are considered be true.

Should you use bool in C++?

It is something C programmer use, but C++ programmers should avoid, since C++ has bool . bool is a language integral type whose supported values are just true and false . When converted to int true becomes 1 and false becomes 0.


1 Answers

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.

like image 99
NPE Avatar answered Sep 23 '22 05:09

NPE