in_array vs strpos for performance in php
As I often work with large datasets, I'd go with isset
or !empty
on an associative array and check for the key, like @Barmar suggests. Here is a quick 1M benchmark on an Intel® Core™ i3-540 (3.06 GHz)
$test = array("read", "edit", "delete", "admin");
echo "<pre>";
// --- strpos($rights,$test[$i%4]) ---
$rights = 'read,edit,delete,admin';
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (strpos($rights,$test[$i%4]) !== false) { }}
echo ' strpos(... '.round(microtime(true)-$mctime,3)."s\n";
// --- in_array($test[$i%4],$rights) ---
$rights = array("read", "edit", "delete", "admin");
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (in_array($test[$i%4],$rights)) { }}
echo 'in_array(... '.round(microtime(true)-$mctime,3)."s\n";
// --- !empty($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (!empty($rights[$test[$i%4]])) { }}
echo ' !empty(... '.round(microtime(true)-$mctime,3)."s\n";
// --- isset($rights[$test[$i%4]]) ---
$rights = array('read' => 1, 'edit' => 1, 'delete' => 1, 'admin' => 1);
$mctime = microtime(true);
for($i=0; $i<=1000000; $i++) { if (isset($rights[$test[$i%4]])) { }}
echo ' isset(... '.round(microtime(true)-$mctime,3)."s\n\n";
echo "</pre>";
The winner is isset
:
strpos(... 0.393s
in_array(... 0.519s
!empty(... 0.232s
isset(... 0.209s
strpos
is the fastest way to search a text needle, per the php.net documentation for strstr()
:
If you only want to determine if a particular needle occurs within haystack, use the faster and less memory intensive function strpos() instead.1