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 takes integers from 0 to 100 and returns color information for that number. Imagine a progress bar with a red 0 and a green 100. This is what the function does.
So, I understand: if this function always returns the same color for each input (i.e. the colors do not depend on time / user / session), the best 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',
And I check it. And the unexpected happens! The new function, which returns the result only from the array of results, takes twice the time as the original function, which must calculate the result each time it calls.
Why is this? Are PHP arrays slow ? Is there a faster way to store function results to speed up the function? Maybe a switch? If / elseif / else conditions? Another way to work with arrays?
source share