|
Posted by Matthew Weier O'Phinney on 06/05/05 20:16
* Andy Pieters <mailings@vlaamse-kern.com>:
> Of these two expressions, which one is faster?
>
> if(!(is_null($customMenu)) && (is_array($customMenu)))
> $menu=$customMenu;
> else
> $menu=array('Documentation','Settings');
>
>
> OR
>
> $menu=(!(is_null($customMenu)) && (is_array($customMenu))?$customMenu:$menu);
>
> Anybody have any documentation on this?
Try benchmarking it. Use microtime(), and do each in a for loop that
iterates 1000 times or so.
$timestart = microtime(true);
for ($i = 0; $i < 1000; $i++) {
if (!is_null($customMenu) && is_array($customMenu)) {
$menu = $customMenu;
} else {
$menu = array('Documentation', 'Settings');
}
}
$timeend = microtime(true);
$timestart2 = microtime(true);
for ($i = 0; $i < 1000; $i++) {
$menu = (!is_null($customMenu) && is_array($customMenu))
? $customMenu
: array('Documentation', 'Settings');
}
$timeend2 = microtime(true);
$time1 = $timeend - $timestart;
$time2 = $timeend2 - $timestart2;
echo "if-else took $time1 seconds\n";
echo "ternary took $time2 seconds\n";
(Note: the above works in PHP5; you need to do some additional
contortions in PHP4 to get similar functionality with microtime.)
From my own benchmarks, it looks like the if-else is slightly faster.
--
Matthew Weier O'Phinney | WEBSITES:
Webmaster and IT Specialist | http://www.garden.org
National Gardening Association | http://www.kidsgardening.com
802-863-5251 x156 | http://nationalgardenmonth.org
mailto:matthew@garden.org | http://vermontbotanical.org
Navigation:
[Reply to this message]
|