0

I need to a perform an action based on the value of a string. I think that if I use a switch statement it will be slower than using multiple ifs and strcmp function. Thoughts?

Method 1:

switch ( $string ){
   case 'Hello': //do stuff
       break;
   case 'Howdy': //do stuff
       break;
}

Method 2:

if ( strcmp($string, 'Hello') == 0 ) // do stuff
if ( strcmp($string, 'Howdy') == 0 ) // do stuff

Which one will be most effective?

user3704920
  • 617
  • 1
  • 8
  • 19
  • 1
    `strcmp` is weird here. `$string === "Howdy"` is fine. – Halcyon Jan 20 '15 at 16:18
  • @Halcyon wouldn't `strcmp ` perform better than simply comparing strings? like `$string === "Howdy"`? – user3704920 Jan 20 '15 at 16:25
  • Probably not, `strcmp` is a function and `===` is a language construct. Calling a function is relatively slow. If you want to know for sure write a benchmark. My guess is that `strcmp` is easily 100x slower. – Halcyon Jan 20 '15 at 16:27
  • @Halcyon thanks for your reply. Also, I don't think this is a duplicate since the question is the performance value of the comparison in a `switch` versus `strcmp` and not a comparison between `switch/if`. – user3704920 Jan 20 '15 at 16:30
  • The accepted answer covers performance. – Halcyon Jan 20 '15 at 16:32

0 Answers0