Does asking twice give bad performance?

Viewed 4172

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?

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.

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;
}

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.

Related