身份条件"===",性能和转换

jon*_*ohn 9 php comparison performance fuelphp

我总是远离stackoverflow的答案和我所做的任何阅读"==="都优于"=="因为使用更严格的比较,并且你不浪费资源转换值类型以检查匹配.

我可能会以错误的假设来到这里,所以我假设这个问题的一部分是"我的假设是真的吗?"

其次,

我正在处理一种情况,我以字符串的形式从数据库中获取数据"100".

我比较的代码就是这个......

    if ($this->the_user->group == 100) //admin
    {
        Response::redirect('admin/home');
    }
    else   // other
    {
        Response::redirect('user/home');
    }
Run Code Online (Sandbox Code Playgroud)

    if ( (int) $this->the_user->group === 100) //admin
    {
        Response::redirect('admin/home');
    }
    else   // other
    {
        Response::redirect('user/home');
    }
Run Code Online (Sandbox Code Playgroud)

甚至

    if (intval($this->the_user->group) === 100) //admin
    {
        Response::redirect('admin/home');
    }
    else   // other
    {
        Response::redirect('user/home');
    }
Run Code Online (Sandbox Code Playgroud)

是通过手动转换或转换获得的任何完整性(或性能),以便您可以使用identity('===')比较?

Nik*_*kiC 13

在您的特定情况下==是更好的选择.正如您(在代码中可以看到)可能已经发现许多数据库函数将始终返回字符串,即使您获取整数.所以键入严格的比较真的只会膨胀你的代码.

此外,您正在增加潜在的(让我们称其为理论上的)安全风险.例如,(int) '100AB2'会屈服100.在你的情况下,这可能不会发生,但在其他情况下可能会发生.

所以:不要过度使用严格的比较,它并不总是好的.你主要只需要在不明确的情况下,比如返回值strpos.