I made an interesting discovery today.
An if-statement like this:
PHP Code:
if($val == 1){$req = 'yea';}else{$req = 'no!';}
is slower than (I don't know what to call it) inline-if's:
PHP Code:
$req = $val ? 'yea' : 'no!';
My test files:
PHP Code:
// File 1 :"inline-if's"
<?php
// Start timer
$mtime = microtime ();
$mtime = explode (' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$val = 1;
$req = '';
$req = $val ? 'yea' : 'no!';
$req = $val ? 'yea' : 'no!';
[repeat from line 11 to 6478]
// End timer
$mtime = microtime ();
$mtime = explode (' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = round (($endtime - $starttime), 5);
echo $totaltime;
PHP Code:
// File 2: normal if's
<?php
// Start timer
$mtime = microtime ();
$mtime = explode (' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$starttime = $mtime;
$val = 1;
$req = '';
if($val == 1){$req = 'yea';}else{$req = 'no!';}
if($val == 1){$req = 'yea';}else{$req = 'no!';}
[repeat from line 11 to 6478]
// End timer
$mtime = microtime ();
$mtime = explode (' ', $mtime);
$mtime = $mtime[1] + $mtime[0];
$endtime = $mtime;
$totaltime = round (($endtime - $starttime), 5);
echo $totaltime;
The average parsing-time of the first file is
0.00614.
The average parsing-time of the second file is
0.01138.
I tested this on WinXP SP2, Apache 1.3, PHP 4.3.5, localhost.
This is not really groundbreaking, but for performance-freaks like me, it is definatly interesting. Plus, the first method is much more readable(especially when you have 5 lines one after another).

Bookmarks