switch ($foo)
{
case 1:
$bar = "%";
break;

default:
$bar = "1";
break;
}
if ($foo == 1)
{
$bar = "%";
}
else
{
$bar = "1";
}

I'm probably splitting hairs, but which of the above is more efficient?

    I'm probably splitting hairs, but which of the above is more efficient?

    You are definitely trying micro-optimisation that does not matter. My emprical tests show that the if-elseif-else version is slightly faster than a switch-case version. However, the difference is so slight as to be negligible in real use.

    In your example, the switch does not make sense and obfuscates the flow control. If you really did need to compare multiple possible values to a single value, use a switch, or consider an array with in_array() or array_search().

      In a simple case like that, there's probably not much difference either way. A switch may gain you time though in situations where you have elseif's in there, as each elseif has to re-evaluate the conditional expression, whereas it is only evaluated once in a switch.

        A switch may gain you time though in situations where you have elseif's in there, as each elseif has to re-evaluate the conditional expression, whereas it is only evaluated once in a switch.

        Surprisingly, comparing:

        if ($foo == 1) {
        } elseif ($foo == 2) {
        } elseif ($foo == 3) {
        } else {
        }

        and

        switch ($foo)
        {
        case 1:
            break;
        case 2:
            break;
        case 3:
            break;
        default:
        }

        a million times gave this result in seconds:

        $foo  if      switch
        1     0.205   0.249
        2     0.287   0.329
        3     0.382   0.422
        4     0.395   0.395

        I guess that the kind of optimisations possible for a switch for say, a C++ compiler is not so possible in normal PHP execution.

          If those are the values you're getting for a million iterations, I'm not going to choose which to use based on performance. 🙂

            1. It doesn't matter.
            2. Use whichever enables you to create more maintainable code
            3. Developer time is more expensive than CPU time, by a factor of several zillion
            4. If you really, really, really do care, benchmark it.
            5. If you benchmark it, do so in a production-spec environment

            Mark

              5 days later

              Maybe it all depends on . In different situations the speed is different.

                Write a Reply...