Interview question: Which one will execute faster, if (flag==0) or if (0==flag)? Why?
Interview question: Which one will execute faster, if (flag==0) or if (0==flag) ? Why?
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I haven’t seen any correct answer yet (and there are already some) caveat: Nawaz did point out the user-defined trap. And I regret my hastily cast upvote on “stupidest question” because it seems that many did not get it right and it gives room for a nice discussion on compiler optimization 🙂
The answer is:
In the case where
flagactually is a user-defined type. Then it depends on which overload ofoperator==is selected. Of course it can seem stupid that they would not be symmetric, but it’s certainly allowed, and I have seen other abuses already.If
flagis a built-in, then both should take the same speed.From the Wikipedia article on
x86, I’d bet for aJxxinstruction for theifstatement: perhaps aJNZ(Jump if Not Zero) or some equivalent.I’d doubt the compiler misses such an obvious optimization, even with optimizations turned off. This is the type of things for which Peephole Optimization is designed for.
EDIT: Sprang up again, so let’s add some assembly (LLVM 2.7 IR)
Even if one does not know how to read the IR, I think it is self explanatory.