0

Is it true that in C++ command

n & 1

is quicker and uses less memory than

n % 2?

(where n is of type int)

More globally, is there any way to find residue of an integer modulo 2 quicker than using % operator? Thanks in advance.

Deduplicator
  • 44,692
  • 7
  • 66
  • 118
Igor
  • 179
  • 2
  • 7

1 Answers1

5

Which uses more or less memory is highly dependant on the instruction encoding, but n & 1 can be many times faster [1], if the compiler doesn't optimised n % 2 to the same thing. Of course, many compilers will indeed make this optimisation (or one that may do the same thing but cope with negative numbers that have an interesting effect on %, which & doesn't need to "care" about).

Note that, depending on exactly what you want to achieve, negative numbers will need special treatment BEFORE & 1 can be used. If gettting 1 from -1 & 1 is fine, then using & is indeed a valid option, but mathematically a bit weird.

Note also that ALWAYS when comparing performance, you need to make your own benchmark measurements [or understand very well what the a particular compiler produces for a particular processor model], you can't always rely on what you read on the internet - including my posts.

[1] As a comparison, most modern processors perform an AND in a single clock-cycle, and can often perform more than one such operation in parallel. Integer divide, which is used for remainder is definitely not that fast. I happen to have an AMD Optimisation guide from January 2012 for "Family 15" processors. A 32-bit divide operation with "remainder" as the answer can take up to 39 clock-cycles. So, assuming the compiler DOESN'T optimise % into an AND instruction, it is roughly 40-80 times worse to use % than & - assuming of course it is a valid optimization.

Mats Petersson
  • 126,704
  • 14
  • 140
  • 227
  • @PaulR: Like I said in my answer "negative numbers become 'interesting' with `%`". At least gcc will indeed perform an AND instruction when you use `%` with a `2^n` value - but it will then do some extra instructions on signed numbers that make the optimisation a little less efficent. – Mats Petersson Jan 26 '15 at 23:24
  • Sorry - missed that on first reading. – Paul R Jan 26 '15 at 23:25
  • Made it clearer, so hopefully others will "get it immediately". – Mats Petersson Jan 26 '15 at 23:27
  • People also tend to forget that dividing by a power of 2 is equivalent to a bitshift only for positive numbers. – Ben Voigt Jan 26 '15 at 23:51