Well I know that the title makes almost no sense but I could not find a better one to explain my question here.
So I've just started doing challenges on LeetCode and I am on the very first steps for now. But one situation confused me.
So I was solving the question named "Number of 1 Bits" which basically gives you an unsigned integer and wants to know how many 1's are in its binary representation.
So first, I've written this code;
class Solution {
public:
int hammingWeight(uint32_t n) {
int answer=0;
while(n>0)
{
if(n%2)answer++;
n/=2;
}
return answer;
}
};
Then I realised that it has a runtime of 3 miliseconds.
Then I was trying other solutions to optimize it and I've written the fastest code(i think).
class Solution {
public:
int hammingWeight(uint32_t n) {
int answer=0;
while(n>0)
{
if(n%2==1)answer++;
n/=2;
}
return answer;
}
};
So this one had a runtime of 0 miliseconds.
I thought since if(i%2)
makes less comparisons, it would be faster.
The only difference is the condition in the "if command".
So why is if(i%2==1)
is faster than if(i%2)
?
It's not. Both your code will produce the same machine code.
Your measuring method is wrong, you need to loop that function millions times to get a non-bias result and it will be the same.
The lesson? Don't try to optimize the if statement, in most cases you won't be smarter than the compiler