Bitfields might seem more efficient at first glance, but in practice they often cause more trouble than they are worth. And even a flawless implementation usually ends up buying a couple bytes of RAM for a whole lot of CPU cycles.
You’re being flippant, but in the world of latency sensitive computing that’s huge. Memory access is VERY expensive, and cpu math is basically free. Packing bools is an easy big win when performance matters.
I’m not a low-level memory expert, but surely it takes the same amount of time to grab 2 bytes over a single byte? So I don’t think the memory latency really matters here.
It’s not about saving literally one byte. But if you have a data structure that uses a lot of bools, compacting them can be the difference on fitting in a cache line or not. Or if you have a large array, you can fit multiple structs in a cache line.
Moral is: keeping your data compact is really really really important for performance. And bitfields are a good tool to keep data compact.
This is completely ridiculous. You might only be thinking of a few flags in a struct but if you think about things like a black and white array / image, there are plenty of times you want to pack in bits.
for a whole lot of CPU cycles.
Absolutely not. Bit shifting is as cheap as it gets, accessing memory is expensive. You could do 1500 bit shifts in the time it takes to get a single byte from memory that isn't in the TLB. (You can't actually make a cpu only get a single byte though. It will always access two cache lines at a minimum, each being 64 bytes).
It all depends on CPU and architecture. People have no clue how many resource-constrained microcontrollers are around us nowadays. Even good old 8051 will be around for bunch of years until minimal variants of riscv may dominate the market. Sometimes we still have to deal with systems that have KBs of total memory at most.
Bit fields rarely fit the needs due to lack of placement warranty. Good old bitmasks seem to still be the golden standard when it comes to operating on bits in registers.
View all comments
712
u/Large-Assignment9320 Oct 07 '26
Just back all 64 bools inside a good old perfectly aligned 64bit.