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?)
Asked
Active
Viewed 122 times
6
-
1you could create a performance test :) – wake-0 Dec 30 '16 at 20:16
-
Is nr always positive? – apandit Dec 30 '16 at 20:18
-
@apandit It can have any sign. – Stephan Dec 30 '16 at 20:19
-
1Intuitively 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. – gior91 Dec 30 '16 at 20:21
-
1A 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. – Marco13 Dec 30 '16 at 20:22
1 Answers
5
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
.

Community
- 1
- 1

Govind Parmar
- 20,656
- 7
- 53
- 85
-
1Did not know about "Software Engineering Stack Exchange", sorry for maybe posting in the wrong area, and thank you for the answear! – Stephan Dec 30 '16 at 20:24