在PHP什么是速度更快,大的switch语句或数组键查找 [英] In PHP what's faster, big Switch statement, or Array key lookup

查看:330
本文介绍了在PHP什么是速度更快,大的switch语句或数组键查找的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在PHP什么是速度更快,使得大量switch语句,或建立一个数组,并查找关键?

In PHP what's faster, 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.

但是,这不是我在做什么 - 通过code分别运行是新的,阵列将被每次只使用一次。因此,所有的数组哈希需要新鲜每次来计算,我想知道,如果这样做,设置比仅仅有一个switch语句慢。

But that's not what I'm doing - each run through the code is new, 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.

推荐答案

做了一些测试:

array_gen.php:

array_gen.php:

<?
echo '<?
$a = 432;
$hash = array(
';
for($i = 0; $i < 10000; $i++) echo "$i => $i,\n";
echo ');
echo $hash[$a];
';

switch_gen.php:

switch_gen.php:

<?
echo '<?
$a = 432;
switch($a) {
';
for($i = 0; $i < 10000; $i++) echo "case $i: echo $i; break;\n";
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%

然后我修改了循环:

Then I modified the loop to:

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语句或数组键查找的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆