How slow are bit fields in C++

こ雲淡風輕ζ 提交于 2019-12-01 16:27:19

The two examples should be very similar in speed because the compiler will have to end up issuing pretty much the same instructions for bit-masking in both cases. To know which is really best, run a few simple experiments. But don't be surprised if the results are inconclusive; that's what I'm predicting...

You might be better saying that the bitfields are of type bool though.

Unless this is in a very very very tight loop there will be nothing to choose between the two on performance, if performance really matters use bools (ie probably 32-bit values).

Using a struct with only three single bit fields like that will still pad out to at least 32-bits. If you're absolutely concentrated on saving every bit possible have a look at the documentation for your compiler on alignment and padding in structures.

EDIT: One reason to favour bit-fields though is that they make for neater code, and the importance of maintainability shouldn't be underestimated. In comparison to programmer time, computer time is cheap!

General advice for this kind of question: set up a simple program comparing your situation as exactly as you can (operations, hardware, etc.) and measure your performance difference yourself.

For this question on bitfields vs masking, I doubt you'll see significant performance differences - the bitfield code may need a shift or two more than masking, depending on the compiler. Whether that's noticeable in your application or not is something you need to answer. There's a big difference in the considerations for mask-programmable embedded code vs. desktop applications, for example.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!