Why use flags+bitmasks rather than a series of booleans?

后端 未结 10 2090
猫巷女王i
猫巷女王i 2021-02-05 03:29

Given a case where I have an object that may be in one or more true/false states, I\'ve always been a little fuzzy on why programmers frequently use flags+bitmasks instead of ju

10条回答
  •  伪装坚强ぢ
    2021-02-05 03:56

    It was traditionally a way of reducing memory usage. So, yes, its quite obsolete in C# :-)

    As a programming technique, it may be obsolete in today's systems, and you'd be quite alright to use an array of bools, but...

    It is fast to compare values stored as a bitmask. Use the AND and OR logic operators and compare the resulting 2 ints.

    It uses considerably less memory. Putting all 4 of your example values in a bitmask would use half a byte. Using an array of bools, most likely would use a few bytes for the array object plus a long word for each bool. If you have to store a million values, you'll see exactly why a bitmask version is superior.

    It is easier to manage, you only have to deal with a single integer value, whereas an array of bools would store quite differently in, say a database.

    And, because of the memory layout, much faster in every aspect than an array. It's nearly as fast as using a single 32-bit integer. We all know that is as fast as you can get for operations on data.

提交回复
热议问题