Suppose you have a class
(or struct
, depending on your language of choice) that has a bool
field. This bool
indicates something important or is some kind of flag. Each class
instance can be accessed as an element of an array, so it has an index.
It seems at first that each class
instance must use one byte for the bool
field. But there is another way—not necessarily better, but more memory-efficient: we can use another array to store each flag as a single bit.
Each byte has 8 bits, so if we want to access the appropriate byte in the array for a class
in our program, we can just its index and divide it by 8. Then a modulo division will give us the exact bit position in that byte.
Is this approach of using separate arrays to minimize memory usage (also called data-oriented programming, or arena allocation) always better? No, it is not—it reduces memory locality in some cases, and causes extra instructions to be executed to address the byte array. But if you have many objects you are dealing with, consider using single bits to represent bools.