PHP性能问题

mcb*_*eav 1 php performance

想知道哪个会更好的表现.该网站将由登录的人和不登录的人查看.对于已登录的用户,该站点几乎相同,只是他们有更多的权限.所以我想知道什么会更有效率.

//选项一

if(isLoggedIn()){
Write the whole web site plus the content the logged in user can access
}
else {
Write the whole website again, minus the content the logged in users can access. 
}

//OPTION TWO
Write the website content and inset the login function wherever i need to restrict the access, so the function would be called a few different times.
Run Code Online (Sandbox Code Playgroud)

我想知道使用选项1对性能是否会更好,因为该函数首先被检查一次,并且不需要再次检查,如果用户登录,则第一个块将被加载,如果用户不是登录后,它将忽略第一个块并加载第二个块.

Dam*_*S8N 5

都不是.最好的选择是检查isLoggedIn一次,保存结果,并在源内执行ifs以在每个位置交换.


Cra*_*ige 5

第二个选项可以忽略不计,但是它是更好的选择,因为它产生更少的代码重复.

此外,如果将isLoggedIn()的结果缓存在静态var中,则不必在每次调用该方法时执行所有检查.您可以检查静态变量并提前跳出.

function isLoggedIn() {
    static $is_logged_in = null;

    if(!is_null($is_logged_in)) {
        return $is_logged_in;
    }

    //... user is known not to have valid credentials

    $is_logged_in = false;

    // ... User has been validated 

    $is_logged_in = true;

    //...


}
Run Code Online (Sandbox Code Playgroud)

  • 最好将它默认为`null`并在`is_null($ logged_in)`为真时检查状态. (3认同)
  • 因为你无法区分实际的"假"和未初始化的"假".因此,对于未登录的用户,它会在每次调用时运行检查.而如果`if(!is_null($ logged_in)){return $ logged_in; 无论结果如何,都允许你缓存调用... (3认同)