简体   繁体   中英

PHP elseif statements; separate elseif, or compressed into one?

I'm basically wondering if there's a difference between enumerating all the possible conditions via separate elseif statements or combining them into one (apart from readability, that is).

Example 1:

if($x == 0)
{
    (condition A)
}
elseif($x == 1)
{
    (condition A)
}
elseif($x == 2)
{
    (condition A)
}
else
{
    (condition B)
}

Example 2:

if($x == 0 || $x == 1 || $x == 2)
{
    (condition A)
}
else
{
    (condition B)
}

Obviously example 2 is more readable, but is it also faster (or otherwise preferred)?

The cleanest option I've seen for your code is the following:

switch($x) {
    case 0:
    case 1:
    case 2:
        (condition A)
        break;
    default:
        (condition B)
        break;
}

You could also do:

if ($x <= 2) {
    // Condition A
} else {
    // Condition B
}

But to answer your question:

Of the 2 statements, theoretically the second would be faster but only because PHP would be parsing 1 statement recursively rather than 3 separate statements. However, the difference is so minuscule that you probably won't be able to accurately measure it. Which means they may as well be identical. My answer above this text would be faster than either of the supplied example because there is only 1 comparison (not 3). But again, the difference is small enough that it may as well be the same.

不,它们在功能上是等效的。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM