Re: What is faster?

From: Date: Sun, 05 Jun 2005 17:16:45 +0000
Subject: Re: What is faster?
References: 1  Groups: php.general 
Request: Send a blank email to php-general+get-216416@lists.php.net to get a copy of this message
* 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

« previous php.general (#216416) next »