Tuesday, October 16, 2012

PHP in_array ultra bad performance (solutions)


If you work on huge data and you care about performance, just go and replace any call to in_array with one of the following alternatives


#1 isset

Change you data structure to be

$yourArr[$val]=1 instead of $yourArr[]=$val

Then

use isset( $yourArr[$val] ) instead of in_array($val, $yourArr)


#2 my_in_array

Create a function as an alternative for in_array (ex: my_in_array )

function my_in_array($needle,$haystack)
{
   
    foreach($haystack as $val)
    {
        if ( $needle==$val){ return true;}
    }

    return false;
  
}

** This function may lead to less performance than in_array on small amount of data
** You may need to change this code (ex: to handle case sensitivity )




No comments:

Post a Comment