3

我的代码正在使用 array_walk 遍历一个数组,该数组包含大约 10.000 个项目。查询需要 5.19 秒来获取记录,但遍历数组需要 19.86 秒。我可能没有什么可以做的来加快速度?

问题以 json 格式返回,并由 jquery dataTables 插件用于创建表。该插件似乎对这么多条目没有问题(至少在 Firefox 上没有)。

我正在使用 laravel 框架。请参阅下面的控制器代码

$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);
4

1 回答 1

2

只需自己循环数组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>';
}
于 2012-10-15T17:07:00.440 回答