简体   繁体   中英

Which way is more efficient?

I'll try to keep this simple. I made twp functions that test something:

//user valid
function validusr(){
    return true;//or false, depends
}
//user in db
function indbusr(){
    return true;//or false, depends
}

Later on, I have this

    if ( !validusr( $myval ) ) return validusr( $myval );       
    else if ( !indbusr( $myval ) ) return indbusr( $myval );            
        else return true;

However, this doesn't seem good to be because I am calling the function 2 times:once to test $myval , and once when I return it. But, if I say, store the value like this:

$result1=validusr($myval);
$result2=indbusr($myval);

        if  (!$result1)  return $result1;       
        else if ( !$result2) return $result2;           
            else return true;

There might be cases when the second statement never runs because the first would always be true, which makes calling the second function useless.

So which one is more efficient? Storing the value and risk it not being used, or calling the function twice when needed, only?

Your logic boils down to this:

If the user is valid AND in the database, return true, otherwise, return false;

You can take advantage of PHP's internal optimiser to determine which functions to call. Using this:

return (validusr($myval) && indbusr($myval));

PHP will execute the first function and look ahead at the expression. If the function returns true it will go on to the next function. If it returns false the expression will be false whatever the next function returns so PHP won't bother calling it and return false immediately.

Similarly, PHP will optimise OR expressions ( $a || $b ||someFunction($c) ) by returning true as soon as it encounters a true value in the sequence. (Thanks to dognose for highlighting that!)

This is great if your functions have no side effects. If you're relying on your second function to have some other effect besides just answering the true/false question this won't work for you.

You can see it working here - try changing the return values of the functions and see what happens when you run it.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM