Hacker Newsnew | past | comments | ask | show | jobs | submitlogin
Which one will execute faster, if(flag==0) or if(0==flag)? (stackoverflow.com)
50 points by solipsist on Jan 8, 2011 | hide | past | favorite | 61 comments


The real correct answer: if it matters, you're already doing something wrong.


If someone asks you 'what is 2+2' the correct answer is not 'if you have to calculate 2+2 by hand you're Doing It Wrong'.

The correct answer is '4'


This is not a 2+2 question.

If someone asks you "how do I dispose of a dead body without the cops knowing about it?" The correct answer is not the simplistic direct answer to that question. Sometimes the correct answer is "why are you doing that? don't do that!"


Exactly.

Furthermore, in this case we aren't even given enough information to derive a "true" direct answer. What's the architecture? The compiler? Hell, we don't even know the language! Assuming x86, gcc, and C, which is a best case assumption (from the standpoint of easily being able to come upon an answer, and test it) we still don't quite know. What optimization level is being used?

Without answers to all of those questions, and likely more, the only possible answer is "if you need to know, you already messed up".


You're right that enough information wasn't provided to get a meaningful answer. I disagree though, that the response to that is 'you messed up' instead of 'give us more info'.


Sometimes it is. Sometimes not. Don't you think the original question was at least interesting in a pedantic way if not useful in practice?

Yes, if you're worried about 1==x vs x==1 then you're probably writing code at the wrong level, but it's still a nice thing to investigate and reason about on a purely academic level.

In those cases, skirting the question by saying "You're doing it wrong" adds nothing to the conversation except to pull in a few "Yeah" shouts from the chorus.


Many people have added to the discussion.

The truly correct answer is (as others have pointed out): you shouldn't have to ask. Because if it actually matters to you then you should be using profiling, timing tools, etc. that will make it trivial to figure out which one is faster.


No. If it matters you have a job involving oses or control systems or game engines and shouldn't be asking on stackoverflow.


No, even then you're doing it wrong. Either: your compiler should optimize it properly and you shouldn't be worrying about it, or you shouldn't be doing it in C anyway.

If the difference between the two is actually important, then chances are your compiler is doing a myriad of other things significantly sub-optimally as well. Most likely far more sub-optimally than the difference between either of those.


Even though most questions are about gluing GUI libraries to databases, that doesn't mean questions about OS or game engines are disallowed.


I think the implication was that if you are programming at that level then you shouldn't be asking beginner questions (instead of just testing yourself).


The first thing that comes to my mind when someone asks such questions (quite often seen in IRC channels), is: "Well, why don't you time both versions and actually measure which is faster?"

Also, premature optimisation is the root of all evil ;-)

There is also an aesthetical side to it. Personally I find constructs like 'if (6.28 < theta) {...}' unpleasant to read. They look like thoughts turned inside out.


I use them conventionally -- it helps me avoid bugs like 'if(foo = 3)' instead of 'if(foo == 3)'. 'if(3 = foo)' just will not compile. The 'if(6.28 < theta)' is just a logical consequence.


My C/C++ compiler will give a warning on 'if (foo=3)'.

Python will throw a SyntaxError on 'if foo = 3:'.


as someone else has mentioned they have been coined yoda conditions, which I love as a name.


OTOH, measuring this kind of things is quite hard - it is only a couple of cycles assuming the optimistic case, so smaller than most measurement methods overhead.

People often wrongly assume that you can just execute many times the thing in a loop, and compute the average, which is the wrong statistic (you want the min, not the average when measing the speed of something which has a fixed cost).

By itself, the question is pretty stupid - maybe that's what the interviewer was getting at ?


Isn't it interesting that x < y, y > x, !(x >= y), and !(y >= x) all express the same thing differently (barring NaNs)? Why should one of them be considered more "inside out" than another? Why does it make a difference if one is a constant rather than a variable? Does one of "x + 2" and "2 + x" seem inside-out as compared to the other? How about "2 * x" vs "x * 2"?


You're right. I think it's just what people are used to. Compare:

"If two gallons is less than the amount of gas in your tank, you should fill it up."

"If you have less than two gallons of gas left in your tank, you should fill it up."

In everyday speech, as well in mathematics, it is usual to state the variable first (what are we're going to compare) and then the amount to which it will be compared.


The first is especially awkward because you forgot to flip the < into a >. It should be, "If two gallons is greater than the amount of gas in your tank, you should fill it up."


The second actually splits the variable across the comparison. ("you have" and "left in your tank").


Depends on the language, interpreter, vm, processor, and compiler and their relevant individual optimization settings.


Code like Yoda, you must not.


The if(0==flag) is perfectly valid for avoiding if(flag=0) bugs.

Of course, I'd use if(!flag)


Any modern should not allow 'if(flag=0)'.

Any non-modern language should flag a warning on that. And this warning should be set to be an error by any reasonable developer.


Personally I'm more against "=" being the assignment operator, which should be ":=". But I have no problems with the actual syntax so long as it's clearly defined what (x = y) returns. (Does it return y? x? true if assignment was successful? Does it call a operator=() function that blows up the moon?) In languages where the line between statement and expression is nil it would be especially odd to flag this as illegal.

Flash Builder's Actionscript compiler has saved me from that a couple times in memory, though, so I agree it should be a warning if you don't wrap it in extra parens. gcc also will complain.


Personally I'm more against "=" being the assignment operator, which should be ":=".

The problem with := is that you run the risk of the Pascal trap, in that no language which uses := for assignment has ever become more popular than Pascal.


In general, I just don't like hitting shift, and so am opposed to :=.


Let's compromise and make it ;=.


I'd rather if the compiler simply determined whether or not it was used as an assignment or comparison and just go with a single =.


What about while? while(flag = 0) looks like a similar error, but while(foo = read()) is a common idiom.


I think some compilers give a warning on while(foo = read()) but not on while((foo = read())).


That would be a broken compiler.


No, I'm pretty sure that's intentional specifically to permit that idiom.


It's usually a warning that you have to turn on explicitly, or one that you can at least turn off (thank heavens).


It's not the choice of keyword that (should) trigger the warning. It's the simple fact that an expression that evaluates to boolean contains an '='. This potential error is trivial for any compiler to flag.


I think PHP allow assignment in 'if'


> Any modern should not allow 'if(flag=0)'.

This is how you set default values for optional argument in Ruby and is very common.


I have never seen "if foo = 0" used to set a value for an optional argument in Ruby. It would either be "def bar(foo=0)" or "foo ||= 0". Can you give any example of what you're talking about?


My mistake. I didn't read parent carefully enough. Although it is common to see something like:

  if(@post = Post.find(params[:id]))
    render @post
  else
    render 'Post not found'
  end


Honestly, this is like arguing tabs vs spaces.


Tabs vs. spaces is basically an implementation detail of the editor. The point is that the code should always look the same.

This is a semantic issue that doesn't even go away in pseudocode.


In C++ flag==0 and !flag are not always the same, but depending on the type of flag, and if that type(or any its parents) has either or both of == or ! operators overloaded.


Pray tell which compiler you are using that won't throw a warning on variable assignment in a condition?


If one side of the expression is longer, putting the shorter one first can improve readability. (Some would argue that you should assign the longer expression to a variable first).

I think that

  if(S_OK == QueryInterface(IID_IUnknown, &p)) {
is clearer than

  if(QueryInterface(IID_IUnknown, &p) == S_OK) {


The correct answer is your debugger.


Faster is not even the most relevant reason why one should (and would) choose 0 == flag.

edit http://news.ycombinator.com/item?id=2082165 hit on it perfectly.


It's still hard to read.


Not when you get used to it.


That's what they said about Lisp and Perl.


I can't tell whether you're just being tongue-in-cheek, or perfectly serious. I hope the former.


Little of both, really. I actually think Lisp is beautiful, although it can be difficult to read. As for Perl...

http://www.foo.be/docs/tpj/issues/vol3_2/tpj0302-0012.html

No excuse.


I don't think you're supposed to be able to get used to obfuscated anything. By that metric, C is equally unreadable: http://ioccc.org/

I've seen very readable perl code, although I won't use that to make sweeping generalizations about the entire language.


To be fair, I never said C was pretty. I have no real problem with Perl aside from its overabundance of punctuation.


It is for those that haven't fully internalized the symmetry of ==. Is it a lack of effort, or a lack of ability?


That's a pretty condescending thing to say. To answer your rhetorical question, we are taught from elementary school to say, "x = 3", not "3 = x". Yes, it's the same, but it's jarring.


I remember getting marked off once in either my algebra 1 or geometry class for leaving some answers in the form "3 = x". (What, you gave me an equation of "5 = 3x - 4"! It's harder to follow the work you make me do if I suddenly swap everything.) Anyway, I never found it jarring, though I can see why others might. (And if you've never had exposure to TI basic.. 3->x.)


TI BASIC kinda reminds me of assembly in that way.


I would say pretty much they'll be the same, but as always it depends on what get the compiler ends up generating. Likely it'll be something like:

mov ax,0x####

mov bx,0000

cmp ax, bx

je equal

I say same cause the order of the data moves into the registers shouldn't matter in terms of perf. I 'guess' If you happen to see a minimal difference it would be because an interrupt happened in the middle of the execution,or there's some funky compiler optimization for one of the cases or if...

ALL GLORY TO THE HYPNOTOAD.


I'll stick with my answer to a highly relevant related question on SO: http://stackoverflow.com/questions/767821/is-else-if-faster-...


depends on number of machine instructions they generate.


Not true in the general case. On some architectures, some instructions take longer than others.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: