我应该在foreach循环括号内放置函数吗?

时间:2015-03-29 10:36:54

标签: php loops

什么更有效?在foreach循环中放置函数...

    $array = array(1, 2, 3, 4, 5);

    foreach (array_keys($array) as $key) {

        # do whatever...
    }

或者在变量之前指定:

    $array = array(1, 2, 3, 4, 5);

    $keys = array_keys($array);

    foreach ($keys as $key) {

        # do whatever...
    }

1 个答案:

答案 0 :(得分:0)

无论哪个看起来更具可读性......虽然后者会比前者使用更多的内存:但在这种情况下都不需要,因为你可以做到:

$array = array(1, 2, 3, 4, 5);

foreach ($array as $key => $value) {

    # do whatever...
}

如果你只需要密钥,你可以使用上面的内容而忽略该值(虽然在语法上你需要指定它)

修改

如果您关注性能和内存使用情况,请使用256k元素的数组进行快速测试(足以在统计数据中给出差异):

#1

foreach (array_keys($array) as $key) {
}

给出

Call time was 0.0466 seconds
Current memory usage: 21.75 MB
Peak memory usage: 42.75 MB

#2

$keys = array_keys($array);
foreach ($keys as $key) {
}

给出

Call time was 0.0335 seconds
Current memory usage: 42.75 MB
Peak memory usage: 42.75 MB

#3

foreach ($array as $key => $value) {
}

给出

Call time was 0.0103 seconds
Current memory usage: 21.5 MB
Peak memory usage: 21.5 MB