Re: could use some suggestions to speed this short piece of code up
| From: | Rene Veerman | Date: | Wed, 20 Jan 2010 17:46:37 +0000 |
| Subject: | Re: could use some suggestions to speed this short piece of code up | ||
| References: | 1 2 | Groups: | php.general |
| Request: | Send a blank email to php-general+get-301271@lists.php.net to get a copy of this message | ||
this is at least 1000% faster
the crux is that array()+=array() is way faster than any array_merge()
operations.
global $hmGenKeys;
$hmGenKeys = 0;
function htmlMicroscope_generateRandomArray ($maxKeys, $maxDepth,
$maxDuration=-1) {
global $hmGenKeys;
if ($maxKeys!==null) {
$hmGenKeys = $maxKeys;
}
$hmGenKeys--;
if ($hmGenKeys<=0) return false;
if ($maxDepth==0) return false;
srand(htmlMicroscope_randMakeSeed());
while ($hmGenKeys > 0) {
$range = rand(0,40);
file_put_contents('countdown.txt', $hmGenKeys);
for ($i=0; $i<$range && $hmGenKeys>=0; $i++) {
$hmGenKeys--;
if ($maxDuration!=-1 && $maxDuration < getDuration()) {
return false;
} else {
$r = array();
switch (rand(1,2)) {
case 1 :
$next = htmlMicroscope_generateRandomArray (null,
$maxDepth-1, $maxDuration);
if ($next!==false)
$r += array(
htmlMicroscope_randomValue(3) => $next
);
break;
case 2 :
$r += array(
htmlMicroscope_randomValue(3) => htmlMicroscope_randomValue(20)
);
break;
}
}
}
}
return $r;
}
function htmlMicroscope_randomValue($maxLength) {
$r = '';
switch (rand(0,9)) {
case 0 : $r = rand (0,100000000); break;
case 1 : $r = rand (0,100000000) / rand(1,100) / 3; break;
default:
switch (rand(0,1)) {
case 0:
for ($i = 0; $i < $maxLength; $i++) {
$r.= unichr(rand(0,hexdec('ffff')));
}
break;
case 1:
for ($i = 0; $i < $maxLength; $i++) {
$r.=chr(rand(ord('a'),ord('z')));;
}
break;
}
break;
}
//echo $r.'<br/>'.$maxLength.'<br/>';
return $r;
}