it seems very slow for php to process mass amounts of strings, is there anyway i can improve the speed of it?
the code i was trying to write will make a image into a string of RGB values for later use
it would be something like this
$string = "255:255:253#12:12:23#33:34:24"/*an output of a $SIZE = 3 image*/
the problems is that when $SIZE is big like 256, it would take up to 1 second to produce the string
$r = "";
$g = "";
$b = "";
for($y = 0; $y <= $SIZE-1; $y++){
for($x = 0; $x <= $SIZE-1; $x++){
{$r .= $arr2[$y][$x]["R"].":";}
{$g .= $arr2[$y][$x]["G"].":";}
{$b .= $arr2[$y][$x]["B"].":";}
}
}
$r = rtrim($r, ":");
$g = rtrim($g, ":");
$b = rtrim($b, ":");
$str_a .= $r."#".$g."#".$b;
Based on your given code, we can reverse-engineer the structure of $arr2 to (assuming R, G and B are integer from 0 to 255):
Given that your
$SIZEis set to256, you will have a total of256*256=65536arrays further containing arrays with key-values forR,GandB, resulting in total of256*256*3=196608 integersin 3 levels of hierarchy. No surprise your code is slow!I think the best strategy here is to try to reduce the total number of items in your array.
Given that instead of encoding single cells as “R, G, B” triples, you could encode all values in a single integer. Such as instead of:
Given that
0<=r,g,b<=255, you could encode$arr2as:Now of course you need to unpack the color value inside your loop as well. This can be achieved by:
This modification alone would cut one level of hierarchy from your array completely.
While running your original code with $SIZE=256, my average execution speed in my settings was 0.30 secs. With the given refactoring, I was able to reduce this to 0.10 secs cutting your calculation time to 1/3 of the original.
You will still have a lot of work to do if you wish to improve the performance, but I hope this gives you an idea on how you could proceed.