Which is Faster and better, Switch Case or if else if?

后端 未结 8 1230
予麋鹿
予麋鹿 2020-11-28 05:52

Which is the better and fastest methods : if or switch ?

if(x==1){
  echo \"hi\";
} else if (x==2){
  echo \"bye\";
}

switch(x){
  case 1
    ...
  break;
          


        
相关标签:
8条回答
  • 2020-11-28 06:29

    According to phpbench.com, if/elseif is slightly faster, especially when using strict comparison (===).

    But it'll only really matter if you want to shave off microseconds on a function that'll be called thousands of times.

    0 讨论(0)
  • 2020-11-28 06:29

    It's depending on usage. If you have fxp status (online, away, dnd, offline...) its better use switch.

    switch(status)
    {
    case 'online':
    ...
    }
    

    But if you wanna something like this

    if ((last_reply.ContainsKey(name)) && (last_reply[name] < little_ago))
    

    or

    if (msg.ToString()[0] == '!')
    

    its better use if else.

    0 讨论(0)
提交回复
热议问题