PHP. Is array_map faster than foreach?
In terms of performance, is this the best option?
While in the object:
Case number 1
public function test( $array ) {
return array_map( array( $this, 'do_something_to_element' ), $array );
}
Case number 2
public function test( $array ) {
$return = array();
foreach ( $array as $value ) {
$return[] = do_something_to_element( $value );
}
return $return;
}
There are other options, of course, and many examples can be filled in. I saw comments that array_map is slower than foreach.
Are array_map / array_walk functions generally faster than foreach loops with similar needs?
I believe this answers your question and is current as of 2015-01-22
Foreach performance, array_map with lambda and array_map with static function
array_map, although more elegant, is unfortunately slower in PHP. Especially when used with a closure.
I tested this on a symfony project just now, been on google because it seems so significant. Script went from 160ms using foreach()
up to 260ms using array_map()
. Considering the size of the application, which grows quite a lot from one method call.