4 ms·
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 actua
by Luyt 16y ago
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.
- daleharvey 16y agoas someone else has mentioned they have been coined yoda conditions, which I love as a name.
- wnoise 16y agoIsn'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"?
- Luyt 16y agoYou'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.
- wnoise 16y agoThe second actually splits the variable across the comparison. ("you have" and "left in your tank").
- __david__ 16y agoThe 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."
- cdavid 16y agoOTOH, 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 ?
- xyzzyz 16y agoI 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.
- Luyt 16y agoMy C/C++ compiler will give a warning on 'if (foo=3)'. Python will throw a SyntaxError on 'if foo = 3:'.