Test your variables!


When PHP throws you an error, there is always a reason. My dev box is set up to throw me everything it finds, and as I am working on a code that needs strong optimization, a question crossed my mind. Before I ask the question, here’s the (simplified) error-ing code:

// Function is called many times (~1M)
function doSomething($arrTest) {
  $strName = $arrTest[0];
  $strType = $arrTest[1];
  $strColor = $arrTest[2];
}

$arrTest = array('banana', 'fruit');
doSomething($arrTest);

Of course, $arrTest[2] doesn’t exist, and PHP, as friendly as it is, works perfectly, just throwing a notice. But, is it faster to use a variable directly not knowing if it exists, or instead, test it every single time you use it?

Nothing speaks better than a good test, so here it goes:

$strTest = '';
$arrTest = array('first row');

for ($i=0; $i<1000000; $i++) {
  $strTest = $arrTest[$i];
}

In this test, only the first index is set, so from $i=1 to $i=1000000, PHP won’t find a value in the array and set $strTest to null.

Let’s try it with a variable test:

$strTest = '';
$arrTest = array();
$arrTest[0] = 'first row';

for ($i=0; $i<1000000; $i++) {
  $strTest = isset($arrTest[$i]) ? $arrTest[$i] : 0;
}

Results:

The second test performs twice as fast than the first one.