【问题标题】:How come a simple PHP array lookup is so slow? Am I doing something wrong here?为什么一个简单的 PHP 数组查找这么慢?我在这里做错了吗?
【发布时间】:2013-08-27 07:51:49
【问题描述】:

我有以下功能:

function percentToColor($percent){
    $minBrightness = 160;
    $maxBrightness = 255;

    // Remainins?
    $brightness = ((($minBrightness-$maxBrightness)/(100-0))*$percent+$maxBrightness);
    $first = (1-($percent/100))*$brightness;
    $second = ($percent/100)*$brightness;

    // Find the influence of the middle color (yellow if 1st and 2nd are red and green)
    $diff = abs($first-$second);
    $influence = ($brightness-$diff)/2;
    $first = intval($first + $influence);
    $second = intval($second + $influence);

    // Convert to HEX, format and return
    $firstHex = str_pad(dechex($first),2,0,STR_PAD_LEFT);
    $secondHex = str_pad(dechex($second),2,0,STR_PAD_LEFT);

    return $firstHex . $secondHex . '00';
}

此函数接受从 0 到 100 的整数,并返回该数字的颜色信息。想象一个进度条,红色为 0,绿色为 100。这就是函数的作用。

所以我明白了:如果这个函数 always 为每个输入返回相同的颜色(即颜色不依赖于时间/用户/会话),更好的主意是创建一个PHP数组加上结果吧?

所以我重写了函数:

function percentToColorNew($percent){
   $results = array(
      0 => 'ff0000',
      1 => 'fe0500',
      2 => 'fd0a00',
      3 => 'fc0f00',
      // ... continues with 4, 5, up until 100 ...
      99 => '03a000',
      100 => '00a000'
   );
   return $results[$percent];
}

我测试它。而意想不到的事情发生了!新函数只返回结果数组中的结果,将 时间加倍 作为每次调用时都必须计算结果的原始函数。

这是为什么? PHP 数组是否这么慢?是否有更快的方法来存储函数结果以加速函数?一个开关,也许? if/elseif/else 条件?使用数组的不同方式?

【问题讨论】:

    标签: php arrays function


    【解决方案1】:

    这很慢,因为您每次调用函数时都在初始化数组。

    在函数之外设置数组,它应该会快得多。快速而肮脏的例子:

    $results = array(
        0 => 'ff0000',
        1 => 'fe0500',
        2 => 'fd0a00',
        3 => 'fc0f00',
        // ... continues with 4, 5, up until 100 ...
        99 => '03a000',
        100 => '00a000'
    );
    
    function percentToColorNew($percent){
        global $results;
        return $results[$percent];
    }
    

    编辑:或者更好地使用static 关键字:

    function percentToColorNew($percent){
        static $results;
        if(!is_array($results)) {
            $results = array ( ... );
        }
        return $results[$percent];
    }
    

    【讨论】:

    • 将数组传递给函数和使其全局可访问之间有什么区别?
    • 将其作为参数传递给函数与使其在性能方面全局可访问相同。
    • 使用全局没有意义。 OP可以通过这种方式在函数内部初始化数组static $result;if (null == $result){// code here}
    猜你喜欢
    • 2019-12-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-06-13
    • 2016-03-03
    • 2013-06-28
    • 2023-01-19
    相关资源
    最近更新 更多