I am not low low low low level, but don't you still need to tell it that it is a bool in the first place? Or is that just determined by whatever stores/retrieves it?
At some point, regardless of whether its a "compiled" language or not, there is a point where its reduced to simple machine instructions. Doesnt matter when that happens. Doesnt matter if you call it compilation or interpretation. By the time the code is in program memory, the concept of type has fallen away.
In machine code, all load/store instructions just work on 1,2,4,8, or maybe 16 or 32 bytes. It's the compiler's responsibility to make sure, e.g., an int doesn't get used as a float, and that doesn't have to be done at runtime.
In languages where it is always done at runtime, like Python, you're going to be wasting a lot of bits on identifiers, and a lot of instructions on inspecting them, so the bit-conscious wouldn't be using that language in the first place.
I don't know how many languages there are that fully compile all the way to machine code and then still use type tags all the time, since it's easy for a compiler to resolve most or all of the function overloads ahead of time, but lots of languages need type tags sometimes.
For example, C++ will attach type tags to objects when that type has inheritance relationships. (Those are actually pointer-sized, 64 bits, so that they can directly point to the set of identifiers for that object's correct virtual functions).
Yes, you declare a bool. But because the system can only work in whole memory addresses, you still use a whole byte for just a single bit of information.
std::vector<bool> is the space optimized implementation that reuses one byte for multiple bools, but it runs into problems like not working with pointers.
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.
Whole lot of cpu cycles? Isolating the wanted bool is a bitshift and an & 0b1, and if you have to calculate the bitshift offset one more add. Depending on what youre doing you could also do masked operations.
In any case, the packing of bools increases the arithmetic intensity if your code which is a huge win since 90% of actual, real life programs are not actually compute bound, but memory bound.
Depends on what you do with them (like most things). If they represent things that can be multiplied with bitwise math like address spaces they're super definitely worth it.
Don't use bitfields to save on RAM, use bitfields to use bitwise math. If you're only ever using individual values from the bitfield and they're not related variables then that probably isn't worth it. I'm willing to believe there are some RAM cases in the corner cases, but never needed to personally.
Bitwise math though people, bitwise math is how I made a queue at work over 100x faster in a hot path.
With transmission the framework will often do that for you if it's a bool, but depending, maybe? If you're cool enough to be writing low level transmission code and not using a library nowadays though, I suppose it's possible.
I've never run into memory constraint like that, not saying it doesn't exist but you'd need to have a lot of boolean like things you're tracking to make that worth it with modern hardware. It would need a special use case... I think. Most memory optimizations I do are like... flyweight patterns, removing redundant copies of things, not overfetching, and fixing people being objectively stupid/lazy. In my world at least there's a lot of low hanging fruit before going this hard.
x86 has the bt instruction, which generally makes bit tests cost the same as using a bool. ARM has a similar tbnz instruction. If you're losing a non-negligible number of cycles, chances are something is wrong somewhere.
Really just different efficiencies. If you want to store a handful of bools, yeah. If you want to store a billion of them... then you probably hide them in a class with its own bit lookup and bit flipping methods.
Oh, but it gets better than that: there is absolutelyno guarantee that std::vector<bool> acts as a bit field! Maybe it's a bit field. Maybe it's actually a vector of bool. Nobody knows!
That’s unique to the vector<bool> specialization. All other instantiations of std::vector are guaranteed to be contiguous.
Genuinely, vector<bool> is perhaps the most glaringly dumb choice in the C++ standard. A vector should be a vector, and the standard should provide a dynamic bit field for cases where you do want packed bit flags.
To give a bit of suggestion as to why this might be (though not to justify it, it's a stupid choice), the idea might be that you have a contiguous sequence of addresses that contain bits for the vector, but depending on processor design it may be more convenient to have the individual data-containing units of the bit field in different orders.
E.g. if you have a std::vector<bool> that is internally treated as an array of u32s then the indices within each u32 may look like either the contiguous
u32: 0 1 2...
byte: |0 1 2 3|0 1 2 3|...
or the discontiguous
u32: 0 1 2...
byte: |3 2 1 0|3 2 1 0|...
Though the spec doesn't specify any of that, it just makes a vague non-guarantee of non-contiguity.
Hey, it's still used sometimes. I've used it in high speed drivers, where every single extra byte decreases latency of the overall reaction. And bools for registers are stored like that as well because a single 4 byte variable literally manipulates a physical memory block
Bitboards in stuff like chess engines (64 bits, 64 squares, wow!)
I've screwed around with it for things like sieve method for finding primes. Also tried storing only multiples of 6 +/-1 for 1/3 of a bit per number, so a few gig of memory can hold like 100 billion numbers.
Yeah, bit flags are nice. I've had more than a few cases where functions just kept accumulating boolean parameters, and at a certain point, you just realize that a bitflag makes the whole thing easier to deal with.
Back in college I wrote what I dubbed the OctoBool which used bitwise operators to let you store 8 bools inside a single byte. I thought maybe it could be useful for embedded development that I was starting to get into.
On PLCs (industrial programmable controllers), such data types are usually built-in. When memory (and sometimes bus bandwidth) is very limited and you process a lot of digital (1/0) signals, packing signals together in bytes does indeed become useful.
Well it is. Sort of. It just has one actually relevant data bit but computers usually (almost always) work with bytes as the smallest inseparable unit of data. Any data type smaller than that is just using less of the available space within the byte. In case of a bool, that's 7 unused bits (so there are actually 4 more sleeping guys missing in the meme). But you can technically optimize this by using a 1-byte datatype to store 8 bools in one bit each. In very specific scenarios where you have millions upon millions of bools in memory for some reason, this can add up.
Edit: Also I don't know if there are compilers that already do this bit-packing optimization automatically on e.g. a struct with multiple bools. Afaik this is something you must implement manually but I might be wrong.
But to balance it out, the C++ standard makes it worse by not committing to it one way or the other. A contiguous vector of bool objects is a completely valid underlying representation, as is a tightly packed bit field. Both have substantially different properties that need to be smoothed over by the standard library.
So let’s say I do need millions upon millions of bools. What would be the best method of packing this? I can’t imagine using a char to map out 8 bools is efficient
You just treat it as a multi-dimensional array where your sub-arrays are word bits long, eg `(q, r) = divMod(i,wsz); bit_i = (words[q] >> r) & 1;` and viola!
These ops are very CPU friendly, so they aren't really a bottleneck even in the worst case, and power of two word sizes eg 32 = 2^5 bits optimizes the divmod to two superfast bit instructions to eg `q = i >> 5; r = i & 31`.
A cache miss is a much bigger deal. The real downside is that it breaks normal pointer access, unless your architecture supports bit-addressing.
In C structs, if you have multiple fields that have same underlying data type (eq. uint8_t ) you can give the compilers a hint about number of bytes needed for that field, and the compiler packs them into the underlying datatype sized spaces and does the bit shifts and masking for reads and writes targeting these fields. But you have to tell the compiler how many bits you want for each manually, it never happens automatically.
It would lead to various problems if compilers did this. In languages with pointers and references, you can make a pointer to a boolean field or variable. You can’t make a pointer to a specific bit though so usual pointer semantics totally break down. I guess the compiler would have to disallow pointers to packed booleans, or use some combination of address and bit index for pointer values, but that sounds like quite a can of worms, right?
The performance cost of reading and writing a specific bit may or may not be worth it for a given use case.
I understand that it also leads to data races and concurrency issues, but I’m not super knowledgeable about that
if you have a lot of bools in your code it might be wise to map each bit in a byte position-wise to represent different true/false values, I think some game engines might already be doing that.
Sure, a byte is not technically defined to always be 8 bits and there have been really old computers using anything from 6 to 48 or something per byte. But like... Name one system in use today that is not some really obscure and niche industrial/embedded device that does not use 8 bits per byte. I literally couldn't think of any.
In the olden times, bits were precious enough that you could actually address data by the bit, but on modern systems you can't. There are a lot of datatypes that have wasted space in them due to architectural constraints.
Languages have bitwise operations. If you decide to store many bools in one variable and do individual bit addressing, it's actually very easy. You either AND it with a mask or shift and AND it with a 1 and check if it's 0 or 1 afterward. Given that most languages nowadays treat 0 as false, you can have something like "if (var >> 2 & 1) then" construction, which works. This often can be done in one instruction and is usually quite fast, actually.
If my memory serves me right, it’s not “fast” because “hey look at me I’m more optimized in terms of data amount needed” but more because there’s a greater likelihood that the bool that is needed to be referenced in the form of a bitmask will be found in cache. A cache miss will be slower than accessing a bitmask bit value as well as accessing an actual bool’s value in ram. Why is it more likely to be in cache? I forget maybe someone else could explain.
This scenario is certainly happening, but if your code is written not a horrible way, prefetch will get your variables into cache by the time they are needed, so this kind of thing shouldn't be a major issue.
A variable has higher likelihood to be in cache if it's used repeatedly because prefetch takes temporal locality into account, among other things. On modern CPUs the speed of the execution of individual instructions between logical and arithmetic operations will be about the same, but you might win in speed in cases where you either need to check multiple booleans vs performing fewer bitwise operations. There are also some situational hacks that can allow for expression optimization using bitwise operations. But this kind of thing shouldn't be your go to thing. Write readable code first, do fancy stuff when and if you need it.
Not necessarily 1 byte. Like some windows BOOLs are (were?) typedef to int, so probably 4 or 8 bytes. And Python built bools on their arbitrary precision int type, so they're... some weird size, and the size is different for True and False
Unfortunately, it doesn't work like that in any languages I use. If you set any bit in a boolean's byte, the boolean is now true. This is why you often see crazy shit like:
bool a = !(!(b))
to guarantee that there's either a 1 or a 0 in the boolean.
Ehh, you probably could optimize it a bit by storing multiple bools in a single byte, and do it automatically but that kind of space optimization is useless in 99% of software
I honestly never used them, and we were forbidden from using C++. Only plain C all the way with assembly sometimes so there as little unexpected behaviour as possible
Modern computers are constructed in such a way that they can only really address byte-aligned memory. The performance gains we get as a result far outweigh the loss of space that treating a boolean as a full byte results in.
In typical implementations of C (therefore most languages) a Boolean only consumes one bit of you either use a bit fields (not common anymore) or store them in an array, if you don’t want to waste space they need to be in multiples of 8 on byte addressed systems. Some other languages might never actually concatenate booleans into single bits of you don’t implement the bit masking yourself. I’m not sure if any languages manage to make individual booleans waste zero space but realistically it probably doesn’t matter unless you’re absurdly resource constrained.
It’s much worse. While you can use vector packing and pointers, for when the data structure is at rest in memory, while your bool is in use by a program routine’s memory safe private allocation (not a memory pointer!), it gets unpacked into an integer of the size and bitness of the processor it is running on, because the data needs to be aligned to its address size. Some caveats, if the processor has hardware support for mismatched bitness (like some ARM, MIPS, or RISC-V processors do, if I recall). On Intel and AMD CPUs operating in long mode (amd64), that typically means a 64-bit integer value is used, and 63 bits are wasted until the boolean value is dereferenced and the memory freed.
If you ever programed an Arduino and needed every last bit, there's no way you'd accept this. When I'm coding for microcontrollers, if I need one bool, well now I have at least 7 more perfectly usable bool for free. You get bonus points for creating a struct to save bytes for alignment reasons.
For the learners: For a single bool, no problem, do this, it's cleaner. If you're storing 1M bools, find or write a bitfield class that packs every bit and use that. You get a massive speedup for doing pretty much any operations on this due to better memory access (reading 512 bools in a row is the same cost as reading 1 due to 64b cache line) and bitwise operations are practically free compared to memory access time.
Unfortunately CPUs are designed to have a byte be the smallest addressable memory segment, so sub 8 bit variables are more difficult than they're worth.
At a previous job, the security permissions, displayed as check boxes in the ui, were stored in the DB as a single number, and that number was a float. We knew it changed when we toggled things, but the value was opaque to us. We had scripts that pushed known “magic numbers” into this field to init new hires to known patterns based on position/department, but they were just big integer numbers hard coded into ps1 files
One day, while poking around, I found old documentation on what this was and how to manipulate it, and then I was able to automate doing security additions and removals that we normally did by hand.
The whole array of checkboxes was stored into an array in a certain order, and those bools were bit wise pushed into a single number, so the whole number was a packed map of 28 bools.
The reason it was stored as a float in the db, was at the time they came up with this, the only DB type that had enough “space” to hold up to a 28bit number was the 4byte (32bit) MONEY field, thus giving it a cents/float value
I was able to update those known magic numbers to add in new bits, and we could mass add/remove single bits by doing bitwise and’ing
It was a fun time after that discovery.
Don’t be afraid to be clever in your code people, but document the hell out of it
Computers nowadays work with bytes, if they worked with bits, I guess this wouldn't happen, but I much rather like this, it's not like we have storage issues.
I don't get it? As long as you define the bools next to each other, they'll fill up the byte before moving on to the next. How it works on a PLC at least, I don't know of anything else that could care about this level of inefficiency.
That's not how it works in the majority of low level programming languages; the primary reason for that is that single bits aren't addressable.
As far as I can tell that's also true in PLC-land. Structured Text dictates BOOL has a logical size of 1 bit, but both codesys and beckhoff use a full byte. C and C++ will also use a full byte. There's ways to pack bits, but it usually comes at the cost of addressability.
38
u/tehtris Oct 07 '26
I am not low low low low level, but don't you still need to tell it that it is a bool in the first place? Or is that just determined by whatever stores/retrieves it?
2.7k
u/Futurity5 Oct 07 '26 •
A meme that's not AI related? In this economy?
712
u/Large-Assignment9320 Oct 07 '26
Just back all 64 bools inside a good old perfectly aligned 64bit.
356
u/OxDEADFA11 Oct 07 '26
Meanwhile std::vector<bool>:
281
u/N-partEpoxy Oct 07 '26
I know, let's make vector<bool> a specialization that uses just one bit per bool. What could go wrong?
170
u/Spinnenente Oct 07 '26
nobody is stopping you from storing all your bools in a single long
welcome to optimization only neccessary before you were born.
64
u/Sermuns Oct 07 '26
uint4_t
30
u/Dank_Nicholas Oct 07 '26
Back in college I wrote what I dubbed the OctoBool which used bitwise operators to let you store 8 bools inside a single byte. I thought maybe it could be useful for embedded development that I was starting to get into.
28
u/Randomguy32I Oct 07 '26
Shouldn’t a bool just be a single bit?
23
u/bluej130 Oct 07 '26
true
8
u/dfwtjms Oct 07 '26 edited Oct 07 '26
Bitmasking is an option
6
u/hydbird Oct 07 '26
jvm allocates 8 bits for a boolean smh
6
u/tiajuanat Oct 07 '26
Unless you're using basic or visual basic or something like the DEC PDP-1 which used
-1for true.Which meant that false was always 0 and
NOTwas simply a negation6
u/NewryBenson Oct 08 '26
This is why you store all your bools in an array thay way you are not wasting bits.
13
u/PixelBrush6584 Oct 07 '26
C++ stays winning because of bitfields
bool var0 : 1;
bool var1 : 1;
bool var2 : 1;
bool var3 : 1;
And all four of them together share a byte!
4
u/enternoescape Oct 07 '26
If you ever programed an Arduino and needed every last bit, there's no way you'd accept this. When I'm coding for microcontrollers, if I need one bool, well now I have at least 7 more perfectly usable bool for free. You get bonus points for creating a struct to save bytes for alignment reasons.
4
u/fugogugo Oct 08 '26
4 bit bool???
4
u/azaleacolburn Oct 08 '26
I think we're missing a few bits, right? Half-byte memory alignment isn't really a thing.
5
u/Dry_University137 Oct 07 '26
"My brother in christ this is the most false statement ive ever seen!"
Pov youre a 0
2
u/XxDarkSasuke69xX Oct 10 '26
Average group project
1
u/SlackBytes Oct 07 '26
Accurate
1
u/Stormraughtz Oct 07 '26
now doing meme mapping for all my configurations
1
u/DogmaticParadigm87 Oct 07 '26
Seven bits padding the headcount so one can carry the team. Then vector<bool> shows up and lays off the other seven.
1
u/cbehopkins Oct 07 '26
September that never ends....
1
u/cl0rm Oct 07 '26
8051 MCU had some bit addressable registers for that reason.
1
u/CeeMX Oct 07 '26
I’ll just invent a 8xBool datatype and get rich
1
u/egstitt Oct 07 '26
Are you trying to land an Atari 2600 on the moon? Yeah nobody cares
1
u/SaintWillyMusic Oct 07 '26
the fear of assembly is palpable
1
u/Almostasleeprightnow Oct 08 '26
There’s a Pixar movie here somehow
1
u/isr0 Oct 08 '26
Welcome back to school… I guess.
1
u/wardenpat Oct 08 '26
false false false true
1
u/GenericLib Oct 08 '26
Are we building functions or using functions?
1
u/master-goose-boy Oct 08 '26
Post on this sub that made me lol after long time… GJ OP!
1
u/Maximum0versaiyan Oct 08 '26
Word!
1
u/SnooGiraffes8275 Oct 08 '26
this is what i've started using bitwise flags when i have the option
1
u/VoraciousTrees Oct 08 '26
Gross. Bitpack your bools.
1
u/DadAndDominant Oct 08 '26
Mmm succint data structures
1
u/JackNotOLantern Oct 08 '26
You missed 4
1
u/ganjlord Oct 08 '26
Before George Boole invented the concept of true and false people would tell obvious lies constantly since no one could tell the difference
1
u/hamfraigaar Oct 08 '26
You don't need two bools until you need 9 boolean values. Until then, it's all flags.
1
u/ANewPeace Oct 08 '26
1
u/Impressive-Log5708 Oct 08 '26
For the learners: For a single bool, no problem, do this, it's cleaner. If you're storing 1M bools, find or write a bitfield class that packs every bit and use that. You get a massive speedup for doing pretty much any operations on this due to better memory access (reading 512 bools in a row is the same cost as reading 1 due to 64b cache line) and bitwise operations are practically free compared to memory access time.
1
u/Ursomrano Oct 08 '26 edited Oct 08 '26
Unfortunately CPUs are designed to have a byte be the smallest addressable memory segment, so sub 8 bit variables are more difficult than they're worth.
1
u/Ottorius_117 Oct 08 '26
I miss having flags and having to understand the data stream. everything now is just
*data dump*
1
u/Uberfuzzy Oct 08 '26
At a previous job, the security permissions, displayed as check boxes in the ui, were stored in the DB as a single number, and that number was a float. We knew it changed when we toggled things, but the value was opaque to us. We had scripts that pushed known “magic numbers” into this field to init new hires to known patterns based on position/department, but they were just big integer numbers hard coded into ps1 files
One day, while poking around, I found old documentation on what this was and how to manipulate it, and then I was able to automate doing security additions and removals that we normally did by hand.
The whole array of checkboxes was stored into an array in a certain order, and those bools were bit wise pushed into a single number, so the whole number was a packed map of 28 bools.
The reason it was stored as a float in the db, was at the time they came up with this, the only DB type that had enough “space” to hold up to a 28bit number was the 4byte (32bit) MONEY field, thus giving it a cents/float value
I was able to update those known magic numbers to add in new bits, and we could mass add/remove single bits by doing bitwise and’ing
It was a fun time after that discovery.
Don’t be afraid to be clever in your code people, but document the hell out of it
1
u/DJcrafter5606 Oct 10 '26
Computers nowadays work with bytes, if they worked with bits, I guess this wouldn't happen, but I much rather like this, it's not like we have storage issues.
1
u/SneakyWineBoy Oct 10 '26
Nibble?
1
u/autumnal-lights Oct 12 '26
dude packing sucks, simd helps but gotta align it and then sometimes u gotta do weird like shifts and like thingies
-1
u/Alacritous13 Oct 08 '26
I don't get it? As long as you define the bools next to each other, they'll fill up the byte before moving on to the next. How it works on a PLC at least, I don't know of anything else that could care about this level of inefficiency.