One of the small things that people new to C++ find surprising is the way booleans are printed - instead of something like “false” or “true”, “0” and “1” show up in the output. Ok, this may not be the prettiest format, but at least this makes to_string conversion trivial. Right? Well, recently I’ve seen this conversion significantly contributing to CPU usage in one of our services.
Even though I didn’t have much hopes for improving it, just out of curiosity, I benchmarked the first implementation that came to my mind, that leverages the fact that false is 0 and true is 1, and compare its performance with std::to_string.
Turns out this naive implementation is 3.9X faster!
That’s a pretty high price to pay for generic functionality. Same approach can be used for stringifying many other values within a limited range and even if the range is not limited, it’s possible to special-case the subrange with values that are serialized most often.
Since booleans are not very strongly typed, personally I prefer to wrap them into domain concepts depending on the use-case. Maybe something like
and with a little template metaprogramming it’s easy to support alternative representations
so output depends on the chosen representation
I’ve intentionally used explicit conversion to const char* because unlike conversion to bool it’s not completely free and is probably something that developers must explicitly request.
As always you’re welcome to play with this code in compiler explorer and share your thoughts!