NYCPHP Meetup

NYPHP.org

[nycphp-talk] equal (==) vs identical (===) and casting

Rolan Yang rolan at omnistep.com
Tue Feb 24 01:17:54 EST 2009


Konstantin Rozinov wrote:
> Hey guys,
>
> Some more questions.
>
> 1. Is there a significant speed difference between the equal operator
> (==) and the identical operator (===)?  Should I even be concerned
> about this?  For example, if I know a variable will be of type INT
> 100% of the time, and I pass it to a function which expects the
> variable to an INT, should I use even use === inside the function when
> doing comparisons?  Or is using === in this case just a waste of time?
>
> 2. What's the best way to cast?  For example, is it best to use (int)
> $variable or intval($variable)?
>
>
>   
Questions like this amuse me.

Not surprisingly, === is faster. If the two compared values are both 
INT, it's faster but not by much.
If the two compared values are not the same type and one is a string, 
then equals (==) takes twice as long.
Unless you are running a huge number of comparisons, it shouldn't make 
much of a difference.

Here is a blog entry about micro-optimization:
http://www.codinghorror.com/blog/archives/001218.html

And here is a script to test it for yourself:

<?php

// Rolan Yang - rolan at omnistep.com

$a = "42"; // change these to different types for fun
$b = 42; // change these to different types for fun
$i = 5000000; // iterations

print "== vs === speed test\n\n";
print "a=".gettype($a)."\n";
print "b=".gettype($b)."\n\n";
$s=getmicrotime();
print "Equal (==) \nstart:$s\n";
for ($x=0;$x<$i;$x++) {
    if ($a==$b) {}
}
$e=getmicrotime();
print "end:$e\nTotal:".($e-$s)."\n\n";

$s=getmicrotime();
print "Identical (===) \nstart:$s\n";
for ($x=0;$x<$i;$x++) {
    if ($a===$b) {}
}
$e=getmicrotime();
print "end:$e\nTotal:".($e-$s)."\n";

function getmicrotime() {
    list($x,$y)=explode(' ',microtime());
    return ($x+$y);
}





More information about the talk mailing list