【发布时间】: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 条件?使用数组的不同方式?
【问题讨论】: