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

后端 未结 10 2269
猫巷女王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:52

    1. Space efficiency - 1 bit
    2. Time efficiency - bit comparisons are handled quickly by hardware.
    3. Language independence - where the data may be handled by a number of different programs you don't need to worry about the implementation of booleans across different languages/platforms.

    Most of the time, these are not worth the tradeoff in terms of maintance. However, there are times when it is useful:

    1. Network protocols - there will be a big saving in reduced size of messages
    2. Legacy software - once I had to add some information for tracing into some legacy software.

    Cost to modify the header: millions of dollars and years of effort. Cost to shoehorn the information into 2 bytes in the header that weren't being used: 0.

    Of course, there was the additional cost in the code that accessed and manipulated this information, but these were done by functions anyways so once you had the accessors defined it was no less maintainable than using Booleans.

提交回复
热议问题