By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
424,946 Members | 744 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 424,946 IT Pros & Developers. It's quick & easy.

which one will execute faster flag==0 or 0==flag and why?

P: 3
if of the following will execute faster
Expand|Select|Wrap|Line Numbers
  1. if ( flag == 0) 
  2. {
  3. }
Expand|Select|Wrap|Line Numbers
  1. if ( 0 == flag) 
  2. {
  3. }
Oct 20 '10 #1
Share this Question
Share on Google+
2 Replies

code green
Expert 100+
P: 1,726
insignificant I would say.
But I bet if(!flag) is faster still.
Oct 20 '10 #2

Expert 100+
P: 983
It all depends on what assembly code the compiler generates. Essentially, do "0 == flag" and "flag == 0" compile down to the same code, or not?

Then there are the questions of how the system executes the assembly language level comparison command. Various computers will behave differently, depending. On a PDP-11 or VAX, the entire test is boiled down to one memory instruction which may be 10 or 12 bytes long, depending on the "addressing mode" used for the operands. Who knows if loading an immediate "0" followed by a memory fetch to a stack location is faster than the other way around. Or perhaps it's one simple test instruction, depending on the command set available.

Lastly ... a really good optimizer will eliminate the whole code sequence, as there is nothing to do as the consequent of the test. In this case, execution time for the "if" statement is exactly zero.

Cheers! :)
Oct 20 '10 #3

Post your reply

Sign in to post your reply or Sign up for a free account.