Friday, August 10, 2012

Testing strings in PHP

Continuing from my last post on testing int's, I was curious about strings as well. Now strings are a bit easier to test in PHP than int's, so I'll skip some of the back story and get to the good stuff.

As far as I can tell, there are two valid methods for testing the validity of string variable: is_string($var) and (string)$var === $var. Now is_string is certainly easier to remember, but is it as fast?

The Testing:

I created a simple test strategy, create a set of both valid and invalid values, loop through them 100,000 times and see which takes the least amount of time. Here is my code:

<?php
require_once('../class/Timer.inc');
$timer = new Timer();

$testArr = array(123,'123',12.3,'12.3','1e9','0115',0115,0xFF,'0xFF','a',array(),array(5),array('b'),'',null,true,false);
$loops = 100000;

echo '<h2>Testing is_string($var)</h2>';
$timer->reset();
for($i=0;$i<$loops;$i++){
    foreach($testArr as $v){
        test_is_string($v);
    }
}
echo $timer->elapsed();

echo '<h2>Testing (string)$var === $var</h2>';
$timer->reset();
for($i=0;$i<$loops;$i++){
    foreach($testArr as $v){
        test_typecast($v);
    }
}
echo $timer->elapsed();

function test_is_string($var){
    return (is_string($var));
}
function test_typecast($var){
    return ((string)$var === $var);
}
?>

The Conclusion:

test_is_string: 0.82858300209045
test_typecast: 0.75825190544128

I was pleasantly surprised by this result... but it does turn out that (string)$var === $var is faster than is_string($var).

No comments:

Post a Comment