user997112
user997112

Reputation: 30655

Performance benefit of replacing multiple bools with one int and using bit masking?

I have a C++ application where I use multiple bools through, to check conditions for IF statements. Using cachegrind my branch misprediction is about 4%, so not too bad. However, I do need to try and increase the performance.

Would it be worthwhile to replace 12x bools with a single int. I am on 64-bit Red Hat and I believe bools are represented using 4-byte ints. Therefore I am using 48 bytes, rather than 12 bits.

If I was to use bit masking I think I would still need to store bit patterns for accessing specific bits in the overall int. Would the need to store these bit patterns offset the bytes saves from reducing number of pools and therefore make this idea pointless?

Upvotes: 1

Views: 513

Answers (2)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727047

Although the only way to find out for sure is to try it out, there are several considerations that may influence your decision.

First, the amount of storage would go down: you would not have to "store bit patterns for accessing specific bits in the overall int", because these patterns would become constants inside your program "baked into" the binary code.

Second, you should look at the use pattern of your flags. If you often check combinations of several flags, you may be able to replace some of these checks with a single masking operation.

Third, you should consider the aspect of writing the data back: with separate bool values each write goes to its own location, while a solution with flags would be writing to the same byte or two each time that you need to modify your flags. On the other hand, modifying several flags at once can be done in a single write.

Finally, you should consider the question of readability: your program is bound to become more complex after this change. The the gains in performance may be too small in comparison to losses of readability, because the code will run faster when the hardware become faster in a few years, but less readable code would remain less readable forever.

Upvotes: 2

TNA
TNA

Reputation: 2745

The only solution to know for sure is profiling. Using ints may even be slower on some architectures since accessing single bits may involve some bit shifting and masking.

Upvotes: 0

Related Questions