Can I always use 1-bit booleans?

In my opinion, one bit is all you need for a binary variable of type bool . Is it really a bad decision to explicitly tell all bool to use only 1 bit?

 struct Banana { // little fields bool on_off : 1; bool yes_no : 1; bool left_right : 1; bool alive_dead : 1; bool in_out : 1; }; 

Edit:

I know that the address of the field cannot be specified. Any other flaws?

+4
source share
3 answers

If you have a lot of things, this saves space. But it adds at least an additional AND or OR statement for each clear / set / check operation on a regular single-byte solution.

In the whole scheme of things, if you really do not have a HUGE number, then probably there is no use.

+6
source

There time / space / synchronization is traded.

Obviously, you can store 32 times as many bits in the same space.

However, to access a separate bool, you need at least a masking operation and probably a shift (although this can be optimized under certain circumstances).

This has consequences if several control threads try to change the boolean values ​​because you changed the simple record for your update to read / change / write, so now you need to add synchronization.

+3
source

I came across several good compilers / architectures / functions in which moving boolean elements to bit fields greatly improved the quality and performance of the code.

Unfortunately, GCC is not one of those compilers (or was not the last time I tested this).

When everything is in order, storing several Boolean elements in one register can ease a lot of pressure in the register, which eliminates a lot of spills on the stack and makes the rest of the code much more efficient.

If the architecture has a sufficient set of instructions for processing bits, then verification and manipulation operations can be compact or more compact than comparable operations to extract logical data from entire registers or, even worse, to stack.

As a rule (even on x86), bit-packing of logical data should lead to more efficient code, but the limitation is the compiler.

+2
source

Source: https://habr.com/ru/post/1497196/


All Articles