I understand that array_filter() should costs more than for/foreach because
it is a function call that call another function for each item, while the
for/foreach is a language constructor that works on a way totally different
and its optimized for this kind of job.
foreach($items as $item) { if(expr($item)) { $result[] = $item } }
array_filter($items, function($item) { return expr($item) } )
But there are some possibility to create some runtime optimizer for cases
like that, and "understand" that array_filter() should works like
for/foreach? JS have some kind of optimization and functions is faster than
constructor for cases like that: http://jsben.ch/pZmLf.
I have done some benchmarks with a 60 seconds cycle.
https://pastebin.com/zGmE4pxm - for/foreach -> 17.06 mi cycles
https://pastebin.com/5E2VwHYm - array (prepared function) ->
5.49 mi cycles (-67.82%)
https://pastebin.com/jSA9ZBqt - array (prepared var function) -> 3.30 mi
cycles (-80.66%)
https://pastebin.com/YPdCmphJ - array_filter (inline) -> 3.14 mi cycles
(-81.58%)
I think that array_filter() cost will keep the same, once that it is a
function and I belive that it is already optimized, but the callable could
be optimized to "not be a function internally", working like a constructor.
And maybe it could be applied to other functions like array_map().
--
David Rodrigues