IF x SWITCH - Simulating

Asked

Viewed 145 times

-4

I believe that all of us always time to make some deals in conditions with few values.

I made a test between the IF and the SWITCH.

All content, was created to SIMULATE a more identical structure possible between the IF and SWITCH.

Class file: ifXswitch.php

<?php

class Teste {


    public function fc_if($v) {

        // Marcador de tempo 1
        $t1 = microtime(true);


        // Script
        if ($v == 1) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(1); }
        elseif ($v == 2) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(2); }
        elseif ($v == 3) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(3); }
        elseif ($v == 4) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(4); }
        elseif ($v == 5) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(5); }
        elseif ($v == 6) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(6); }
        elseif ($v == 7) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(7); }
        elseif ($v == 8) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(8); }
        elseif ($v == 9) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(9); }
        else { echo 'Número inválido'; }


        // Marcador de tempo 2
        $t2 = microtime(true);


        // Tempo final
        $t3 = $t2 - $t1;


        return $t3;
    }

    public function fc_switch($v) {

        // Marcador de tempo 1
        $t1 = microtime(true);


        // Script
        switch ($v) {

            case '1':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(1);
            break;

            case '2':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(2);
            break;

            case '3':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(3);
            break;

            case '4':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(4);
            break;

            case '5':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(5);
            break;

            case '6':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(6);
            break;

            case '7':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(7);
            break;

            case '8':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(8);
            break;

            case '9':
            echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(9);
            break;

            default:
            echo 'Número inválido';
            break;
        }


        // Marcador de tempo 2
        $t2 = microtime(true);


        // Tempo final
        $t3 = $t2 - $t1;


        return $t3;
    }


    public function calcula($v) {

        $vf = pow($v,5);

        sleep(1);

        return $vf;
    }


    public function resultado($t_if, $t_switch) {

        echo '<hr>';
        echo '<br> Tempo IF: ' . $t_if;
        echo '<br> Tempo SWITCH: ' . $t_switch;

        if ($t_if < $t_switch) $r = 'IF';
        elseif ($t_if == $t_switch) $r = 'Empate';
        elseif ($t_if > $t_switch) $r = 'SWITCH';
        else $r = 'Erro';

        echo '<br> Menor tempo: ' . $r;
    }

}

?>

Executioner: mitrotime.php

<?php

include_once 'ifXswitch.php';

$exemplo = new Teste();
$t_if = $exemplo -> fc_if(9);
$t_switch = $exemplo -> fc_switch(9);
$exemplo -> resultado($t_if, $t_switch);

?>

In the execution of the test, varies a lot, time wins the IF time the SWITCH, and even incredibly gave draw once.

I would like to know, among them, if one has an advantage over the other in some aspect (e.g., with numbers the SWITCH would be better !?), or if it comes to need and organization ?

  • 3
  • @Updated article... check there please...

  • 1

    This example is probably not the best as every set of ifs could be reduced to echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula($v);

  • It is that I did thinking of keeping the "structure" equal between them, to have the same amounts of conditions... I used numbers, but it could also be string... and yet I had to put the sleep(1) because I was giving 0.

  • 2

    Whenever you need to compare PHP performance, read this answer and the rest.

  • "In PHP the solution is very simple if you need language performance. Change language. "Maniero already comes with 2 feet... rs

  • Even echo itself would be easier with interpolation: echo "<br>$x elevado a 9 = {$this->calcula($v)}";

  • I was trying to generate time because I was giving 0 :'[

Show 3 more comments

1 answer

3


If you run more than a billion loops, you might feel some noticeable difference to the user, but overall they don’t make any difference that it means, 15 conditions for example you wouldn’t notice anything.

Keep in mind that each version of PHP has a different performance, version 7 even is much more efficient than 5, there is also the possibility to use "cache" (it has nothing to do with browser caching), it is similar to JIT (maybe it can be called that), read more on:

To summarize, there is no significant difference between switch and if, what they differ is in their needs, for example the way they used the if and switch you wrote the code already inefficiently in both cases, ie a good part of the performance losses is the way we use and not between types.

The real performance problems are in the way we write and not in two language functionalities, of course there are exceptions, but almost all are only in micro-optimization, which is something that people should stop worrying about and worry more about the serious mistakes that programmers make that will really affect speed

Can someone come here and say that switch is better, but this in PHP is not necessarily a reality, since the way you write your Ifs can result in something more performative (micro-optimization, which is usually insignificant), and as I said there are variations of behavior between versions of PHP, but it’s no use going too far.

What you need to understand is that IF has a better time, place and way of working and the same goes for SWITCH, has a better time, place and way of working.

What will make them both slower is the way you write them, if you know how to deal with the conditions is able to both have the same result (as I said use as needed).

Other factors that can consume more script, type repeated function executions at each check, which is a fairly common error among programmers, for example:

function foo()
{
     return file_get_contents('./version');
}

if (foo() == 1) {
    echo 'Versão 1 do App, atualize para a versão 2 ou 3, este esta obsoleto';
} elseif (foo() == 2) {
    echo 'Versão 2 do App';
} elseif (foo() == 3) {
    echo 'Versão 3 do App';
}

Note that the above code was executed 3 times at least (depending on the contents of the file ./version), now if you do so:

$versao = foo();

if ($versao == 1) {
    echo 'Versão 1 do App, atualize para a versão 2 ou 3, este esta obsoleto';
} elseif ($versao == 2) {
    echo 'Versão 2 do App';
} elseif ($versao == 3) {
    echo 'Versão 3 do App';
}

It will surely run only once the foo(), and how the answer is already saved in the $versao, this will surely make the script more performatic.


Now a suggestion about your code, the problem I see in your codes is unnecessary repetition, for example this:

if ($v == 1) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(1); }
elseif ($v == 2) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(2); }
elseif ($v == 3) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(3); }
elseif ($v == 4) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(4); }
elseif ($v == 5) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(5); }
elseif ($v == 6) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(6); }
elseif ($v == 7) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(7); }
elseif ($v == 8) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(8); }
elseif ($v == 9) { echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula(9); }
else { echo 'Número inválido'; }

It could just be that:

if ($v >= 1 && $v <= 9) {
    echo '<br>' . $v . ' elevado a 9 = ' . $this -> calcula($v);
} else {
    echo 'Número inválido';
}

Okay, you will have reduced your code to two lines, which will certainly improve a little the performance of the parser (which is part of the script interpreter), which is what I mentioned at the beginning of the answer, the problem is more in how we write Ifs than in other factors.

  • The intention was only to simulate the 2 with the same amount of conditions... so they would go through the 9 conditions. I wanted to keep the closest to each other !

  • I understood, but it was another idea the question... I think it has already completely escaped the context... rs

  • I understood everything you said... For example "unnecessary repetition" you posted... I only did it to exactly match IF with SWITCH, fill process to give time.... The question was not in that context... but quiet... can not exclude now...

  • 1

    Just as you didn’t understand the question, friend. I did a SIMULATION to be EQUAL among the 2. It seems like I wouldn’t even be making an IF the way you answered. In the same way that gave me the -1 for not understanding the question, I gave the -1 for finding the answer incorrect. We are with divergent understandings on this issue ! It is quiet ! ;]

  • Wait, I think I put it wrong. Your answer I agree with: "To summarize, there is no significant difference between switch and if, what they differ is in their needs", only here yes, I understood what I meant. But the purpose of the simulation was only to SIMULATE, so I had to make the most of each other and "generate processing". I was "sad" because you treated the question as if it were full of errors ! And on the contrary, I always look for full efficiency in the code... His answer was 90% dealing with "errors" that were purposeful understood ?

  • When downvoter, it was for that reason. Do you agree with me that your answer was out of the context of the question ? If you had just put this little bit I mentioned, it was almost 90% of the question. I’m taking the downvoter because it’s part right and part wrong, you know !?

  • Rest assured, I know the people who know too much here at Sopt, and of course, I will always look carefully at everything they say... I am a mere beginner, and the more I learn, the less I know! rs

  • I never use downvoter atoa, but how I made the choice was about this: your answer focused on 90% usage error, and the errors were purposeful for the simulation. Got it ?

  • 1

    @RBZ the answer did not run out of context, is that Voce did not understand, the answer indicates exactly that you are worrying about things and forget to understand the essential of the language and that with experience of more than 14 years with PHP I tell you, the real performance problems are in the way we write and not in two language languages, of course it has exceptions, but almost all are only in micro-optimization, which is something that people should stop worrying about and worry more about the serious mistakes that programmers make that will really affect speed.

  • Ready ! Perfect ! Here’s your answer: "The real performance problems are in the way we write and not in two language languages, of course there are exceptions, but almost all are only in micro-optimization, what is something that people should stop worrying and worry more about the serious mistakes that programmers make that will really affect the speed" Incrementing: IF and SWITCH are almost equal. ! the focus was that it entered much in the context of the structure (which was purposeful)... but it is quiet ! I thank the help with all sincerity !

  • @RBZ was actually what I said from the beginning of the question, only in other words, to be honest and forgive me, but many people notice that they are just like you, it is not a criticism of evil, but rather constructive, usually lack a little reading practice to absorb the statement of the post, of course I can also try to improve the text and make it more enjoyable, but it is not easy to write and make the text intuitive at first. Anyway I will edit and post this inside the body/content of the answer. Good luck and success!

  • 1

    Criticism can be more effective than praise if we know how to receive it ! I always listen and process ! rs It was a unique topic that "communication language" disrupted the "programming language" rs !! Obg ! Abs !

Show 7 more comments

Browser other questions tagged

You are not signed in. Login or sign up in order to post.