Re: IF or SWITCH

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

 



On Thu, 2006-04-06 at 03:06, Joe Wollard wrote:
>
> um. Did you just stick you tounge out at me? (jk) Actually, Rob brings

Yes, though I forgot the smiley as I'm apt to do :)

>  up a good point. switch statements are not always faster. Here's an
> example from
> http://www.php.net/manual/en/control-structures.switch.php - note that
> it says that in certain circumstances switch may be faster than an if.
> 
> "In a switch statement, the condition is evaluated only once and the
> result is compared to each case statement. In an elseif statement, the
> condition is evaluated again. If your condition is more complicated
> than a simple compare and/or is in a tight loop, a switch may be
> faster."

Specifically the evaluation occurs only once at the entry point, but
that evaluation will occur for every iteration of an enclosing loop.
Given their comments, they are misleading in that the switch will only
be faster if you don't precompute the value to compare in your
if/elseif/else statements. For example, they are saying switch is faster
than the following:

<?php

if( ($foo + $fee) == 0 )
{
}
else
if( ($foo + $fee) == 1 )
{
}
else
if( ($foo + $fee) == 2 )
{
}
else
{
}

?>

Well duh! In practice, what kind of an idiot does that? (ok, ok, don't
answer that ;) However, it may be the case, that the overhead of
precomputing and assigning to a variable in PHP land is a tiny bit
slower than the internal precomputation for switch. Either way,
internally, switch behaves like if/elseif/else and generally only
provides an advantage with respect to code organization or if you want a
particular condition to drop through to other case blocks.

Cheers,
Rob.
-- 
.------------------------------------------------------------.
| InterJinn Application Framework - http://www.interjinn.com |
:------------------------------------------------------------:
| An application and templating framework for PHP. Boasting  |
| a powerful, scalable system for accessing system services  |
| such as forms, properties, sessions, and caches. InterJinn |
| also provides an extremely flexible architecture for       |
| creating re-usable components quickly and easily.          |
`------------------------------------------------------------'

-- 
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