mithilatw
mithilatw

Reputation: 908

What is better to use out of in_array() and || operator?

I am asking this question considering the performance of script. Knowing that PHP arrays don't perform very well, I am wandering which way is the best to go down when in this sort of situations.

Suppose if $x equals to a or b or c or d we need action_a() to execute and if not action_b() to execute..

We can either implement this with || operator as follows;

if($x == 'a' || $x == 'b' || $x == 'c' || $x == 'd'){
       action_a();
}else{
       action_b();
}

Or we can implement this using in_array() as follows;

if(in_array($x,array('a','b','c','d'))){
       action_a();
}else{
       action_b();
}

What I would like to know is which of these two options would perform well:

  1. when the number of possible values for $x are high?

  2. when the number of possible values for $x are low?

Upvotes: 2

Views: 2071

Answers (4)

Shiplu Mokaddim
Shiplu Mokaddim

Reputation: 57690

It depends on the PHP version you are using. On PHP 5.3 in_array() will be slower. But in PHP 5.4 or higher in_array() will be faster.

Only if you think the condition will grow over time or this condition should be dynamic, use in_array().

I did a benchmark. Loop your conditions 10,000 times.

Result for PHP 5.3.10

+----------------------------+---------------------------+
| Script/Task name           | Execution time in seconds |
+----------------------------+---------------------------+
| best case in_array()       | 1.746                     |
| best case logical or       | 0.004                     |
| worst case in_array()      | 1.749                     |
| worst case logical or      | 0.016                     |
| in_array_vs_logical_or.php | 3.542                     |
+----------------------------+---------------------------+

Result of PHP 5.4

+----------------------------+---------------------------+
| Script/Task name           | Execution time in seconds |
+----------------------------+---------------------------+
| best case in_array()       | 0.002                     |
| best case logical or       | 0.002                     |
| worst case in_array()      | 0.008                     |
| worst case logical or      | 0.010                     |
| in_array_vs_logical_or.php | 0.024                     |
+----------------------------+---------------------------+

Best case: match on first element.
Worst case: match on last element.

This is the code.

$loop=10000;
$cases = array('best case'=> 'a', 'worst case'=> 'z');
foreach($cases as $case => $x){
    $a = utime();
    for($i=0;$i<$loop; $i++){
        $result = ($x == 'a' || $x == 'b' || $x == 'c' || $x == 'd' || $x == 'e' || $x == 'f' || $x == 'g' || $x == 'h' || $x == 'i' || $x == 'j' || $x == 'k' || $x == 'l' || $x == 'm' || $x == 'n' || $x == 'o' || $x == 'p' || $x == 'q' || $x == 'r' || $x == 's' || $x == 't' || $x == 'u' || $x == 'v' || $x == 'w' || $x == 'x' || $x == 'y' || $x == 'z');
    }
    $b = utime();
    $ar = array('a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z');
    for($i=0;$i<$loop; $i++){
        $result = in_array($x, $ar);
    }
    $c = utime();

    $Table->addRow(array("$case in_array()", number_format($c-$b, 3)));
    $Table->addRow(array("$case logical or", number_format($b-$a, 3)));
}

Here is utime() is a wrapper of microtime() that provides microseconds in float and $Table is a Console_Table instance.

Upvotes: 3

Barmar
Barmar

Reputation: 782409

For a high number of values, I wouldn't use either method. I would create an associative array whose keys were the possible values, and use isset():

$test_array = array_flip(array('a', 'b', 'c', 'd', ...));
if (isset($test_array[$x])) ...

This has one-time O(n) cost to create $test_array, then checking for a match is O(1).

Upvotes: 3

sybear
sybear

Reputation: 7784

Your first solution works pretty well in case of performance, when you dont need to change anything after, but readablity of the code is getting worse the more values you have to check.

While using array you can dynamically extend it if you need. Also it keeps your code clean.

As far as I know, in_array function has a pretty low performance compared to manual search with a loop.

Also, you can declare so called "map":

$actions = [
  "a" => function(){ action_a() ; },
  "b" => function(){ action_b() ; }
] ;

And after, you do like this:

if (isset($actions[$x])) 
  $action[$x]() ;
else
  do_smth() ;

A small tip: If you are using PHP >=5.4 you can declare a new array just like this:

$array = [1,2,3,4,5] ;
$array[] = "I am a new value to push" ;

Upvotes: 0

Halcyon
Halcyon

Reputation: 57713

Write a benchmark script.

In general though, which variant to pick should hardly ever depend on performance. Especially in super trivial cases where your input data is very very small (say <10).

This most important criteria is always readability.

Only start optimizing code when there is an undeniable performance problem.

Premature optimization is the root of all evil.

Upvotes: 5

Related Questions