Sharky
Sharky

Reputation: 6284

Shorthand if then else performance/optimization in php

Talking about PHP, i would like to ask if there is a difference in performance between these two:

$name=($IsBoy)?"George":"Mary";

vs

if($IsBoy)
{
    $name="George";
}
else
{
    $name="Mary";
}

p.s. if you believe that my code for the "full-longhand" if-then-else is too complex, please provide an example of the most basic code and answer on that.

UPDATE:

I hoped the question is perfectly clear, but it seems people do not get the message. This question is about the THEORETICAL (...yet real and mesaureable) difference in performance (thats why i applied bold and italic in theoretical). Please do not answer by saying what programming style is more readable and that this is too nitpicking to worry about performance.

p.s. 2: by giving emphasis to the word theoretical i try to prevent answers of the type "don't worry its not worth the trouble, its just nanoseconds."

Upvotes: 4

Views: 1481

Answers (3)

Samy Massoud
Samy Massoud

Reputation: 4385

OK this quite interesting

i have did a quick x debug test for your tow examples respectively

and here what i have got

enter image description here

enter image description here

Sure you may have a different result with each refresh put all of them ensure that

Second method is better than first always

even though with each refresh you may find first method take less time occasionally but this is something related with PHP core optimization

regarding to Zend optimizer i didn't test that

Upvotes: 5

Teson
Teson

Reputation: 6736

I often discard if-then-else in benefit of:

$name = 'the expected';
if ([expr]) $name = 'the exception';

Easy to read, less braces and compact.

Upvotes: 0

Jijo John
Jijo John

Reputation: 1375

Both normal ifelse statement and a ternary operator have a slight perfomance difference.You can check the below stackoverflow links for more reference

Click here

Upvotes: -1

Related Questions