string comparison
| From: | Bas Jobsen | Date: | Sat, 27 Jul 2002 16:34:34 +0000 |
| Subject: | string comparison | ||
| Groups: | php.general | ||
| Request: | Send a blank email to php-general+get-109984@lists.php.net to get a copy of this message | ||
Hello,
When should i prefer strcmp() above == or !=?
I have test it out (see code below).
But a == comparison seems to be faster always.
First i thought is was cause, if(strcmp($1,$2)!=0),
needs two comparisons (strcmp and !=). But even
if($1!=$2) is faster then if(strcmp($1,$2)).
Thanks,
Bas Jobsen
<?
function getmicrotime(){
list($usec, $sec) = explode(" ",microtime());
return ((float)$usec + (float)$sec);
}
$t1='hello';
$t2='hello';
$t3='hallo';
?>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if(strcmp($t1,$t3));//nonmatch
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if($t1!=$t3);//nonmatch
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if(!strcmp($t1,$t3));//match
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if($t1==$t3);//match
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if(strcmp($t1,$t2));//nonmatch
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if($t1!=$t2);//nonmatch
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if(!strcmp($t1,$t2));//match
echo getmicrotime()-$start;
?>
<br>
1000x:<?
$start=getmicrotime();
for($a=0; $a<100000; $a++) if($t1==$t2);//match
echo getmicrotime()-$start;
?>
<br>