1

(PHP) for example, i have functions,which execute heavy queries and return TRUE or FALSE. is there any performance difference:

if ( cond1()  &&  cond2() && cond3() && cond4())

or

if (cond1()){
  if (cond2()){

  }
}

because, in the last case, if cond1() is false, then it doesnt execute the other conditions.. is same for the first example?

T.Todua
  • 53,146
  • 19
  • 236
  • 237
  • 1
    No performance difference. In both cases, if `cond1()` returns false, none of the other functions will be called. – Richard Aug 10 '16 at 10:12
  • 1
    If only there was a simple way to test that… *cough* `false && print('hello');` – deceze Aug 10 '16 at 10:15
  • 1
    I have run tests on a PHP sandbox and found that on PHP7 the timings are identical but on PHP 5.6 there are different timings for the differnt IF syntax structure. I was going to elaborate here on that before duplicate locking.... – Martin Aug 10 '16 at 10:22
  • @Martin The byte code may be ever so slightly different, but logically they're identical and there's no performance difference *in the big picture*, i.e. whether `cond2()` gets executed at all or not. Or can you contradict that? – deceze Aug 10 '16 at 10:25
  • I found that on [PHP sandbox](http://sandbox.onlinephpfunctions.com/) running 10k `for` loops on PHP5.6.20 and 7.0.2 there was a very sight difference of around `0.0002` seconds for two loops (1 for each syntax statement (4 `If`'s each)) but the more I think about it the more I suspect the difference is caused elsewhere in the system. Too many unknowns and far too small a variation to be significant. Overall it seemed to show there was a small delay in having all arguments in a single `if` condition. Just interesting, nothing more. @deceze – Martin Aug 10 '16 at 10:44
  • @deceze I will put some details in an answer on the question you linked this one too... – Martin Aug 10 '16 at 10:49
  • frustratingly enough, if I swap the order of the loops it doesn't swap the timings, the second loop is always slower than the first, no matter the syntax so no, I have no interesting conclusion after all. :-( – Martin Aug 10 '16 at 10:58
  • @Martin My main interes was, if the second `cond2()` was executed. so, it is not executed, right? – T.Todua Aug 10 '16 at 13:22
  • 1
    In that respect they're both identical processes, yes – Martin Aug 10 '16 at 13:32

1 Answers1

1

No this has no performance differences.

In this example when condition 1 fails, it doesn't execute the second condition

if ( cond1()  &&  cond2() && cond3() && cond4())
Daan
  • 12,099
  • 6
  • 34
  • 51