Reputation: 15017
Let's say I have 90 'indexes' in my array and I have a function which checks if that value exists in that array, would it be faster if i used strpos with a String instead?
Instead of using in_array()
to
$data = array('John','Mary','Steven');
It will be
$data = 'John.Mary.Steven';
then I'll just strpos()
on that String?
Upvotes: 2
Views: 1820
Reputation: 37913
I was quite sure that use of strpos
will be slower but I made a test below, and it looks like (at least in this particular case - searching for the last element) strpos
is faster than in_array
.
$array = array();
for($i=0;$i<10000;$i++) {
$array[] = md5($i . date('now'));
}
$string = implode('.', $array);
$lastElement = $array[9999];
$start = microtime(TRUE);
$isit = in_array($lastElement, $array);
$end = microtime(TRUE);
echo ($end - $start) . PHP_EOL;
$start = microtime(TRUE);
$pos = strpos($string, $lastElement);
$end = microtime(TRUE);
echo ($end - $start) . PHP_EOL;
Results I'm getting:
0.0012338161468506
0.00036406517028809
Upvotes: 2
Reputation: 24549
According to this test, looping your array and checking with strpos() would be slower than just using in_array(). They claim that in_array() is actually 2.4 times faster than doing a foreach loop with strpos().
On the other hand, a question here on SO seems to indicate otherwise.
Efficiency of Searching an Array Vs Searching in Text.... Which is Better?
If I were you, I would run my own performance tests to see what works best with my specific set of data.
Upvotes: 0
Reputation: 212412
Without bothering to profile it, I'd say that imploding to a string followed by strpos would be slower than PHP's built-in in_array() function.... because you're adding all the overhead of converting the entire array (all 90 elements) to a string before you can even use strpos(). Premature Micro-optimisation isn't a good idea, unless you really need it, and then you should test your ideas.
EDIT
If you're using your own function instead of in_array(), it probably is slower, but raises the question "why"?
Upvotes: 3