Azer Qurbanov Azer Qurbanov -4 years ago 97
PHP Question

Parse huge json data to html with PHP is slow

I have one problem with HUGE JSON DATA. I get json data from backend with service and then i parse the data into HTML with PHP. When i get raw JSON data it takes 2 second, but when I parse it into HTML, it takes too long about 35 seconds. How can i accelerate parse time? Thanks beforehands. Below is my code. I use recursive function and for loops inside that function.

$allstructure=$this->allStructure();

$str='<ul style="padding: 0px;padding-left: 5px;list-style: none">';
for ($x=0;$x<count($allstructure);$x++){

$str.='<li>'.$allstructure[$x]->name.'</li>';
$str.='<li>'.$this->iterator($allstructure[$x]->child).'</li>';

}

$str.='</ul>';

return $str;
}
public function iterator($data)
{

$str='<ul>';

for($i=0;$i<count($data);$i++) {

$str.='<li>'.$data[$i]->name;

$str.='<ul>';

$str.='<li style="display:flex"><input type="checkbox" class="rehbersecim"></li>';

for($z=0;$z<count($data[$i]->listPosNames);$z++){

$str.='<li style="display:flex"><input type="checkbox" class="checkqutu" name="vezife[]" value="'.$data[$i]->listPosNames[$z]->posNameId.'"><p style="width:230px;height:20px"><b>'.$data[$i]->listPosNames[$z]->posName.'</b></p> '.$this->createHtml($data[$i]->listPosNames[$z]->posNameId).'</li>';

}

$str.='</ul>';

if(isset($data[$i]->child)){

$str.=$this->iterator($data[$i]->child);
}
$str.='</li>';

}

$str.='</ul>';

return $str;

}

Answer Source

Your biggest name problem in the code above is the use of for(...; count(...); ...). This forces PHP to do count() every time you go through the loop in question, and you have three of these. When dealing with large data, that will be murderously slow.

Instead of doing it that way, call count() one time for each loop, like so:

$structureCount = count($allstructure);
for ($x=0; $x<$structureCount; $x++){

    $str .= '<li>' . $allstructure[$x]->name . '</li>';
    $str .= '<li>' . $this->iterator($allstructure[$x]->child) . '</li>';

}

A good resource for this kind of thing is http://www.phpbench.com/. For this problem, it shows that calling count() each time through takes approximately 340% as long as calling it once, like I did above. Because you have 3 of these loops effectively nested, this one change means your app may be taking about 3.43 = 39 times as long as it should be.

Also, as TomTom101 pointed out in the comments, you probably don't want to show "HUGE" data to the user all at once. You should consider paging (i.e., showing only part of the data at one time).

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download