I have a "big" array of string and need to find there elements which content specified string.
During tests I have noticed that array_filter is much slower than "foreach and if".
Here is my code for test:
<?php
//Fill array for test by random string
$arr=array();
for($i=0;$i<1000000;$i++) $arr[]="str1".rand(0,999999)."str2";
//Search value
$q='555';
//Test search by foreach and if
$stime=microtime(true);
$res=array();
foreach ($arr as $key=>$val) {
if (strpos($val, $q) !== FALSE)
$res[$key]=$val;
}
//print_r($res);
echo "\n".(microtime(true)-$stime);
//Test search by array_filter
$stime=microtime(true);
$res = array_filter($arr, function ($val) use ($q) { return (strpos($val, $q) !== FALSE); } );
//print_r($res);
echo "\n".(microtime(true)-$stime);
0.10 vs 0.18. foreach+if is faster in ~1.8.
I checked it on php5.6 and php7 on different servers. Numbers are different of course, but multiplier is in range (1.7,2.1).
Why is array_filter slower? I think it must be at least same. Or even faster by optimization for specific task.
Is there anyway to increase speed? Maybe I'm doing something bad in array_filter()
Pleace noticed. It's not about strpos, function for checking must be another.
Data not in MySQL or other, it comes once and need check once as fast as it possible. Storring in DB, indexing and etc will increase time of whole task.
It's not about changing whole array. Just finding a few elements. Usually more then 10.
Also differ is bigger if count of finded elements is bigger.
It's just about how to improve perfomance of search (array_filter).