My code is looping through an array with array_walk and that array contains about 10.000 items. The query takes 5.19 seconds to fetch the records but walking through the array takes 19.86 seconds. There probably isn't anything I can do to speed things up?
The questions are returned in json and used by the jquery dataTables plugin to create the table. The plugin doesn't seem to have a problem with that many entries (at least not on firefox).
I'm using the laravel framework. See controller code below
$start = microtime(true);
$questions = Question::with(array('tags', 'category'))->get();
$now = microtime(true) - $start;
echo "<h3>FETCHED QUESTIONS: $now</h3>";
array_walk($questions, function(&$value, $key) {
$value = $value->to_array();
if (empty($value['category'])) $value['category'] = '--';
if (empty($value['difficulty'])) $value['difficulty'] = '--';
$value['difficulty'] = HTML::difficulty_label($value['difficulty']);
$value['approved'] = HTML::on_off_images($value['approved'], 'approved', 'declined');
$value['active'] = HTML::on_off_images($value['active'], 'active', 'disabled');
$value['edit_link'] = '<a href="' . URL::to('admin/editquestion/' . $value['id']) . '">' . HTML::image('img/icons/pencil.png', 'edit question') ; '</a>';
});
$spent = microtime(true) - $start - $now;
$now = microtime(true) - $start;
echo "<h3>AFTER WALK: $now ($spent)</h3>";
$out = array('aaData' => $questions);
return json_encode($out);
Just loop the array yourself with foreach
to avoid the penalty of making 10000 function calls:
foreach($questions as &$value) {
$value = $value->to_array();
if (empty($value['category'])) $value['category'] = '--';
if (empty($value['difficulty'])) $value['difficulty'] = '--';
$value['difficulty'] = HTML::difficulty_label($value['difficulty']);
$value['approved'] = HTML::on_off_images($value['approved'], 'approved', 'declined');
$value['active'] = HTML::on_off_images($value['active'], 'active', 'disabled');
$value['edit_link'] = '<a href="' . URL::to('admin/editquestion/' . $value['id']) . '">' . HTML::image('img/icons/pencil.png', 'edit question') ; '</a>';
}