PHP array performance
- by dfo
Hi,
this is my first question on Stackoverflow, please bear with me.
I'm testing an algorithm for 2d bin packing and I've chosen PHP to mock it up as it's my bread-and-butter language nowadays.
As you can see on http://themworks.com/pack_v0.2/oopack.php?ol=1 it works pretty well, but you need to wait around 10-20 seconds for 100 rectangles to pack. For some hard to handle sets it would hit the php's 30s runtime limit.
I did some profiling and it shows that most of the time my script goes through different parts of a small 2d array with 0's and 1's in it. It either checks if certain cell equals to 0/1 or sets it to 0/1. It can do such operations million times and each times it takes few microseconds.
I guess I could use an array of booleans in a statically typed language and things would be faster. Or even make an array of 1 bit values. I'm thinking of converting the whole thing to some compiled language. Is PHP just not good for it?
If I do need to convert it to let's say C++, how good are the automatic converters? My script is just a lot of for loops with basic arrays and objects manipulations.
Thank you!
Edit. This function gets called more than any other. It reads few properties of a very simple object, and goes through a very small part of a smallish array to check if there's any element not equal to 0.
function fits($bin, $file, $x, $y) {
$flag = true;
$xw = $x + $file->get_width();;
$yh = $y + $file->get_height();
for ($i = $x; $i < $xw; $i++) {
for ($j = $y; $j < $yh; $j++) {
if ($bin[$i][$j] !== 0) {
$flag = false;
break;
}
}
if (!$flag) break;
}
return $flag;
}