本文介绍了在 PHP、大型 switch 语句或每次都支付数组初始化费用的数组键查找中,什么更快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在 PHP 中,做一个大的 switch 语句,或者设置一个数组并查找 key 哪个更快?

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 the array is faster. But, this is assuming creating the array just once, then looking it up repeatedly.

但这不是我正在做的 - 每次运行代码都是新的,并且数组将每次只使用一次.所以所有的数组哈希每次都需要重新计算,我想知道这样做是否比简单地使用 switch 语句要慢.

But that's not what I'm doing - each run through the code is new, and the array will be used just once each time. So all the array hashes need to be calculated fresh each time, and I'm wondering if doing that setup is slower than simply having a switch statement.

推荐答案

我做了一些测试:

<?
    echo '<?
        $a = 432;
        $hash = array(
    ';

    for($i = 0; $i < 10000; $i++)
        echo "$i => $i,
";

    echo ');
        echo $hash[$a];
    ';

文件switch_gen.php:

<?
    echo '<?
        $a = 432;
        switch($a) {
    ';
    for($i = 0; $i < 10000; $i++)
        echo "case $i: echo $i; break;
";

    echo '}';

然后:

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%

然后我将循环修改为:

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

创建 17576,3 个字母组合.

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.

这篇关于在 PHP、大型 switch 语句或每次都支付数组初始化费用的数组键查找中,什么更快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-05 08:18