3

I was wondering whether it is more efficient to set a function's return to a variable, since if you were to use it in arguments, wouldn't they have to go through the function again?

For instance:

function check() {
    foreach() {
        // insert long foreach loop here
        return true;
    }
}

if(check() == 1 || check() === true) {
    // had to go through the function twice?
}

$check = check();
if($check == 1 || $check === true) {
    // only has to go through the function once
}

I was wondering whether PHP somehow saved the results from the first run through the function or whether it goes through the function each time (which seems inefficient if the arguments are the same - in this case, none).

If anyone wants to suggest a better title or edit it, go ahead.

3
  • 2
    It will go through the function again (unless you have caching in place). Commented Sep 10, 2012 at 21:05
  • 1
    If you want to set the result of the function to be used in multiple places within the scope then it is better to assign it to a variable - based on the reasons you already highlighted. Commented Sep 10, 2012 at 21:07
  • thanks guys! I'm exploring the inner-workings of php! Commented Sep 10, 2012 at 21:09

2 Answers 2

5

It goes through each time. Save it to a variable beforehand, as in your second example.

Sign up to request clarification or add additional context in comments.

3 Comments

thanks! I'm surprised the value isn't saved on the first run, I thought php would have been more efficient
That is up to the programmer :)
The reason PHP doesn't optimize this is that the method could have side-effects. Caching the result of the method call could break the program. Detecting side-effects is possible, but difficult.
0
if(check() == 1 || check() == true) {

is redundant... a simple equality check (==) treats a boolean 'true' as 1 anyways. If you're going to be returning mixed values (int + booleans), you should use the strict equality check:

if (check() == 1 || check() === true)
                            ^^^

In this case, it's not necessary, but consider the case where a function can legitimately return a 0 value, as well as a boolean false to indicate failure. By simple equality tests, 0 == false is true. but 0 === false is false.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.