Re: What is faster?

[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

 



* Andy Pieters <mailings@xxxxxxxxxxxxxxxx>:
> 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@xxxxxxxxxx         | http://vermontbotanical.org

-- 
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php


[Index of Archives]     [PHP Home]     [Apache Users]     [PHP on Windows]     [Kernel Newbies]     [PHP Install]     [PHP Classes]     [Pear]     [Postgresql]     [Postgresql PHP]     [PHP on Windows]     [PHP Database Programming]     [PHP SOAP]

  Powered by Linux