0

Is there a betther way to do this condition:

if ( x > 3 || y > 3 || z > 3 ) {
    ...
}

I was thinking of some bitwise operation but could'nt find anything.

I searched over Google but it is hard to find something related to that kind of basic question. Thanks!

Edit I was thinkg in general programming. Would it be different according to a specific language? Such as C/C++, Java...

Synor
  • 333
  • 1
  • 4
  • 13
  • 2
    There are `&&` in your title, but `||` in the question. Also please add a language tag (C? Java?), this will bring much more attention to your question. – Tagir Valeev Dec 01 '15 at 03:55
  • 1
    For the code in the question, if the variables are unsigned, then `(x|y|z) > 3` is equivalent. However , in C and C++, you should write it as you have it because it expresses your intent clearly and allows the compiler to optimize. Set your compiler to max optimization level and then see what assembly it comes up with. – M.M Dec 01 '15 at 03:56
  • In some languages, you could say `max(x, y, z) > 3`; it is shorter to write, but the code in OP is probably the optimal (execution-wise) EDIT ...for an arbitrary number. @M.M is correct saying that it can be further optimised for specific values (e.g. `2^n - 1`) – Amadan Dec 01 '15 at 03:56
  • 1
    I doubt if fancy bit-wise optimisation would make any difference; what *might* help (assuming a language with [short-circuit evaluation](http://stackoverflow.com/q/9344305/1270789), which is why you are being asked to name your langauge) would be to order the three clauses with the most likely to occur first. – Ken Y-N Dec 01 '15 at 04:01

1 Answers1

6

What you have is good. Assuming C/C++ or Java:

  • Intent is clear
  • Short circuit optimisation means the expression will be true as soon as any one part is true.

Looking at that 2nd point- if any of x, y or z is more likely to be >3, then put them to the left of the expression so they are evaluated first which means the others may not need to be evaluated at all.

For argument's sake, if you must have a bitwise check x|y|z > 3 works, but it normally won't be reduced, so it's (probably*) always 2 bitwise ops and a compare, where the other way could be as fast as 1 compare.

(* This is where the language lawyers arrive an add comments why this edit is wrong and the bitwise version can be optimised;-)

There was a comment here (now deleted) along the lines of "new programmer shouldn't worry about this level of optimisation" - and it was 100% correct. Write easy to follow, working code and THEN try to squeeze performance out of it AFTER you know it is "too slow".

John3136
  • 28,809
  • 4
  • 51
  • 69