I have the following function:
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';
}
This function accepts integers ranging from 0 to 100 and returns the color information for that number. Imagine a progress bar with red at 0 and green at 100. This is what the function does.
So I get the idea: if this function always returns the same color for each input (i.e. the colors aren't time/user/session dependent), the better idea would be to create a PHP array with the results, right?
So I rewrite the function:
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];
}
And I test it. And the unexpected happens! The new function, which only returns the result from the array of results, takes double the time as the original function which has to compute the result every time it's called.
Why is this? Are PHP arrays this slow? Is there a faster way of storing the function results to speed up the function? A switch, maybe? If/elseif/else conditions? A different way of working with arrays?
It's slow because you are initializing the array each time you call the function.
Set up the array outside of function and it should be much faster. Quick and dirty example:
$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];
}
Edit: Or even better use the static
keyword:
function percentToColorNew($percent){
static $results;
if(!is_array($results)) {
$results = array ( ... );
}
return $results[$percent];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With