Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does asking twice give bad performance?

Tags:

php

I have a function:

function getMilk() {
    if($condition == true)
        return "Milk for you, madam";
    return false;
}

Example 1:

if(getMilk()) 
    echo getMilk();

Does the first example make PHP run for milk twice?

Example 2:

echo getMilk(); // don't check for milk first, just get it if they have it

If I was PHP I would rather get the second example. Then I wouldn't have to run to the store checking for milk, then running once more to get it.

Would example 2 be faster/better, or doesn't it matter?

like image 800
OnklMaps Avatar asked Sep 21 '17 10:09

OnklMaps


People also ask

Are performance reviews a waste of time?

1. Performance reviews in most organizations are so bad they do more harm than good. Traditional performance reviews and approaches to feedback are often so bad that they actually make performance worse about one-third of the time. Learn why the manager is key to every aspect of your workplace.

How often should you ask for a performance review?

Many companies do performance reviews as frequently as once per quarter or as far out as once every 18 months. However, most experts recommend you conduct performance reviews every 6-12 months.


3 Answers

Yes, you are calling the function twice. Avoid doing that (because the function can be expensive to call) by doing one of the following:

$getMilk = getMilk();
if($getMilk) echo $getMilk;

You can reduce this to a one line (but unreadable) format:

if ($getMilk = getMilk()) echo $getMilk;

You can also use an inline if ternary, with a fallthrough:

echo getMilk()?:""; //Will echo the result of getMilk() if there is any or nothing.
like image 152
apokryfos Avatar answered Oct 09 '22 11:10

apokryfos


Yes, PHP will call functions exactly as often as you tell it to. The function will be executed twice. You should not do that, since you don't intrinsically know how expensive any particular function is, and/or that may change in the future if you rewrite the implementation details of the function. Especially functions which have side effects (they modify something, e.g. they write to a file) must not be called more often than necessary.

Instead, store the function result in a variable:

$milk = getMilk();
if ($milk) {
    echo $milk;
}

This can even be inlined to:

if ($milk = getMilk()) {
    echo $milk;
}
like image 36
deceze Avatar answered Oct 09 '22 13:10

deceze


The question is theoretical more than anything since the performance difference would be negligible.

That said, in your case, the second approach is fine since false does not translate to any sort of output. So

echo getMilk();

either echos the string, or nothing.

like image 5
Mitya Avatar answered Oct 09 '22 11:10

Mitya