What's faster in PHP, a big switch statement, or an array key lookup where the array initialisation is paid every time?

前端 未结 2 800
半阙折子戏
半阙折子戏 2020-12-14 16:54

What\'s faster in PHP, making a large switch statement, or setting up an array and looking up the key?

Now before you answer, I am well aware that for pure lookups t

2条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-14 17:21

    I did some tests:

    File array_gen.php

     $i,\n";
    
        echo ');
            echo $hash[$a];
        ';
    

    File switch_gen.php:

    Then:

    php array_gen.php > array_.php
    php switch_gen.php > switch.php
    
    time tcsh -c 'repeat 1000 php array.php > /dev/null'
    19.297u 4.791s 0:25.16 95.7%
    time tcsh -c 'repeat 1000 php switch.php > /dev/null'
    25.081u 5.543s 0:31.66 96.7%
    

    Then I modified the loop to:

    for($i = 'a'; $i < 'z'; $i++)
      for($j = 'a'; $j < 'z'; $j++)
        for($k = 'a'; $k < 'z'; $k++)
    

    To create 17576, 3 letter combinations.

    time tcsh -c 'repeat 1000 php array.php > /dev/null'
    30.916u 5.831s 0:37.85 97.0%
    time tcsh -c 'repeat 1000 php switch.php > /dev/null'
    36.257u 6.624s 0:43.96 97.5%
    

    The array method wins every time, even once you include setup time. But not by a lot. So I think I will ignore this optimization and go with whatever is easier.

提交回复
热议问题