Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

identity conditional "===" , performance, and conversion

I've always came away from stackoverflow answers and any reading I've done that "===" is superior to "==" because uses a more strict comparison, and you do not waste resources converting value types in order to check for a match.

I may be coming at this with the wrong assumption, so I assume part of this question is, "is my assumption true?"

Secondly,

I'm dealing specifically with a situation where I'm getting data from a database in the form of a string "100".

The code I am comparing is this...

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

vs.

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

or even

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

is any integrity (or performance) gained by manually casting or converting simply so you can use the identity ('===') comparison?

like image 997
jondavidjohn Avatar asked May 02 '11 05:05

jondavidjohn


2 Answers

In your particular case == is the better option. As you (as can be seen in your code) have probably already found out many database functions will always return strings, even if you fetch an integer. So type strict comparison really only bloats your code.

Furthermore you are adding a potential (let's call it theoretic) security risk. E.g. (int) '100AB2' would yield 100. In your case this probably can't happen, but in others it may.

So: Don't overuse strict comparison, it's not always good. You mainly need it only in ambiguous cases, like the return value of strpos.

like image 81
NikiC Avatar answered Sep 29 '22 18:09

NikiC


There is a performance difference between == and === - latter will be even twice as fast, see Equal vs identical comparison operator. The difference, however is too small to be bothered with - unless the code is executed millions of times.

like image 37
Tomek Avatar answered Sep 29 '22 17:09

Tomek