At 07:48 PM 4/5/2006, Ray Hauge wrote:
I have 57 if/elseif/else statements because of all the different
criteria. Is
it considered better programming practice to use if/elseif/else statements
over a switch(true) case (true && false || true || false) syntax?
Here are two seemingly contradictory bits of advice:
a) Spend more time making your script easy for humans to read than
you spend trying to make it machine-friendly. Servers are bloody
fast and will process your complex set of If-tests faster than you
can click your mouse. Script languages like PHP are purely for the
benefit of us humans; they're easier for us to read and write than
binary machine language. You might be able to slow down a server
with excess disk access and enormous memory demands, but I wouldn't
lay awake at night worrying about how to shave a few thousand machine
cycles off your code. Instead, think of someone (perhaps yourself)
six months or six years from now trying to make sense of your
code. Comment prolifically, name your variables and functions
sensibly, and use plenty of whitespace.
b) Still, there's something to be said for elegance in code-writing,
and efficiency as an aesthetic goal even when it's not a practical
issue. Since you're using it so much, count your array size once and
keep the result in a variable. The computer may or may not be
significantly affected but your code will be much cleaner.
That said, one thing to keep in mind with regard to conditional
processing is that PHP will stop processing a complex conditional if
the conclusion is determined early on. Consider this:
if ($bCondition == true || count($aThings) > 1)
If $bCondition is true, the entire expression will evaluate true, so
it's not necessary for the script interpreter to evaluate
"count($aThings) > 1".
Therefore if you're concerned about processing speed & efficiency you
can improve things by putting first the expressions that will
evaluate more quickly or will eliminate the most possibilities.
Here's a little program that demonstrates this point:
____________________
if (2 == 2 && say("this will appear"))
{
say("test 1 = true");
}else{
say("test 1 = false");
}
if (1 == 2 && say("this won't appear"))
{
say("test 2 = true");
}else{
say("test 2 = false");
}
function say($msg)
{
echo "<p>$msg</p>";
return true;
}
____________________
OUTPUT:
this will appear
test 1 = true
test 2 = false
____________________
The expression "this won't appear" does not appear because PHP stops
evaluating the second if-test after determining "1 == 2" to be false.
My surmise is that the parser first reduces the syntax to "if (A &&
B)" so it knows the number of expressions and their Boolean
relationships, so that when it begins evaluating the granular
expressions in sequence it knows when the overall conclusion is determined.
Regards,
Paul
--
PHP General Mailing List (http://www.php.net/)
To unsubscribe, visit: http://www.php.net/unsub.php