0

Short ciruit question is asked already I know. But i want to know why it dont work here. Does short circuit has some effects due to parallel processing or pipelining.

I faced very strange situation with my code. The code looks like this

foreach($feeds as $k=>$feed)
{
foreach($filtered as $item)
{
 if(($feed['object'] == $item['object']) && (($feed['time']-$item['time'])<10))
   {
   Code....
   }
  }
 }

When i put both condition just like above in same If() block they both get compared. But when i put them in nested blocks they take much lesser time to excute.

Question: Does && work as a short circuit operator. Which mean

if $feed['object'] == $item['object'] fails

($feed['time']-$item['time'] < FEED_TIME) will not be evaluated.

It looks like PHP evaluate cond2 even when cond1 failed.

Can you explain how && actually works in PHP.

Benchmarks

With code as above the if execute for approx 61000 time. taking 27 sec to execute for whole website.

With nested conditions approx 10000 executions for condtion2

$feeds are about 1700 entries where $filtered is 392 entries.

Thanks

s.d
  • 255
  • 1
  • 14

1 Answers1

2

&& and || are short-circuit operators in PHP. You can see it with the following test:

if (0 > 1 && func()) {
    echo "If is true\n";
} else {
    echo "If is false\n";
}

function func() {
    echo "Function called\n";
    return true;
}

If you run this, you should see "If is false", but not "Function called". If you change > to <, you will see "Function called" and "If is true".

I'm not sure how you're determining that your expressions are or aren't being evaluated, since they have no obvious side effects.

Barmar
  • 741,623
  • 53
  • 500
  • 612
  • I want to know then way nested code execute less, if && works that way innermost level of loop should executed same no. of time. Does paralleled processing did something?? – s.d Sep 14 '13 at 22:32
  • PHP is single-threaded, so I don't see how parallel processing could be relevant. – Barmar Sep 18 '13 at 10:10