PHP-array_map是否比foreach快? [英] PHP - Is array_map faster than foreach?

查看:1583
本文介绍了PHP-array_map是否比foreach快?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

就性能而言,哪个是更好的选择?

In terms of performance, which is the better option?

在对象中:

案例1

public function test( $array ) {
    return array_map( array( $this, 'do_something_to_element' ), $array );
}

案例#2

public function test( $array ) {
    $return = array();
    foreach ( $array as $value ) {
        $return[] = do_something_to_element( $value );
    }
    return $return;
}

当然还有其他用途,并且可以填充许多示例.我看到有评论说,在对象中,array_map比foreach循环要慢.

There are other uses of course and many many examples can be populated. I've seen comments that while in an object, array_map is slower than foreach loops.

总的来说,与具有类似需求的foreach循环相比,array_map/array_walk函数的执行速度更快吗?

In general is the array_map/array_walk functions faster to execute than the foreach loops in similar needs?

推荐答案

我相信这可以回答您的问题,并且于2015年1月22日有效

I believe this answers your question and is current as of 2015-01-22

foreach的性能,具有lambda的array_map和具有静态功能的array_map

array_map虽然更优雅,但是在PHP中却很慢.尤其是与闭包一起使用时.

array_map although more elegant is sadly slower in PHP. Particularly if using it with a closure.

这篇关于PHP-array_map是否比foreach快?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆