我的代码在一个array-walk数组中循环,这个数组包含大约10000个项。查询需要5.19秒来获取记录,但遍历数组需要19.86秒。也许我没办法加快速度?
这些问题以json格式返回,jquery datatables插件用来创建表。这个插件看起来没有那么多条目的问题(至少在firefox上没有)。
我用的是拉维框架。见下面的控制器代码
$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);
最佳答案
只需使用foreach
循环数组,就可以避免执行10000个函数调用:
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>';
}