数组遍历使用闭包与循环性能

时间:2015-02-24 17:51:07

标签: php arrays for-loop

性能更好:

array_walk($data,function($item){
 // operation
});

或者

foreach($data as $item){
   // operation
}

1 个答案:

答案 0 :(得分:2)

我可能会在下班回家途中被PHP大师们扯下来发布这个,但这里有一些基准:

define('MAX', 100000);

foreach (range(0, 9) as $run) {
    // array_walk
    $data      = range(0, MAX);
    $startTime = microtime(true);
    array_walk($data, function(&$item) {
        $item = MAX - $item; // Stupid reverse
    });
    echo "#$run: array_walk: ", (microtime(true) - $startTime), PHP_EOL;

    // foreaach
    $data      = range(0, MAX);
    $startTime = microtime(true);
    foreach ($data as &$item){
        $item = MAX - $item; // Stupid reverse
    }
    echo "#$run: foreach   : ", (microtime(true) - $startTime), PHP_EOL;
}

我认为foreach赢了[1]:

#0: array_walk: 0.020771026611328
#0: foreach   : 0.0051238536834717
#1: array_walk: 0.024941205978394
#1: foreach   : 0.0052378177642822
#2: array_walk: 0.024216890335083
#2: foreach   : 0.0053040981292725
#3: array_walk: 0.019840002059937
#3: foreach   : 0.0096650123596191
#4: array_walk: 0.024542093276978
#4: foreach   : 0.0052249431610107
#5: array_walk: 0.01880407333374
#5: foreach   : 0.0051660537719727
#6: array_walk: 0.018791913986206
#6: foreach   : 0.010493993759155
#7: array_walk: 0.022961139678955
#7: foreach   : 0.0051679611206055
#8: array_walk: 0.020010948181152
#8: foreach   : 0.0051009654998779
#9: array_walk: 0.022379159927368
#9: foreach   : 0.0057699680328369

[1]至少在我的系统上:-P