Is there any actual difference in performance? Is it faster? (lets say I use it in at least 100 cases in the same program, would it improve my program in terms of speed?)
Is there any reason to use (nr & 1 == 0) over (nr % 2 == 0) to check for parity?
Asked Answered
you could create a performance test :) –
Hackathorn
Is nr always positive? –
Specialist
@Specialist It can have any sign. –
Arber
Intuitively modulus requires a division that is a more complex operation than bitwise and, so modulus should be slower. As stated by @KevinWallis you can create a performance test. –
Uppsala
A language tag may be helpful. The questions of whether the language has signed types, operator overloads, or about possible optimizations of the compiler (or of the resulting bytecode, for IL languages) are certainly relevant. Otherwise, the question is too broad. –
Kettledrum
This question might be more appropriate on Software Engineering Stack Exchange.
If you're using an optimizing compiler chances are any form of n % <power of two>
will get optimized to n & <power of two minus one>
anyway, since they are equivalent but on pretty much every architecture I can think of the latter is much more efficient.
The former form expresses your intent more clearly, though a lot of developers will recognize n & 1
as a "faster version" of n % 2
.
Did not know about "Software Engineering Stack Exchange", sorry for maybe posting in the wrong area, and thank you for the answear! –
Arber
© 2022 - 2024 — McMap. All rights reserved.