Almost all Android Studio templates for discrete conditions use the usual if instead of switch/case , for example

 if (id == R.id.nav_camera) { // Handle the camera action } else if (id == R.id.nav_gallery) { } else if (id == R.id.nav_slideshow) { } else if (id == R.id.nav_manage) { } else if (id == R.id.nav_share) { } else if (id == R.id.nav_send) { } 

Why is that? Does it give a performance gain?

  • The programmer who wrote the template didn’t like the switch-case - the human factor, perhaps it was an Indian who is known for weakness to head-on solutions and not a desire to think how to make it more "fine" (the third android still reminds some of them: )) - pavlofff

1 answer 1

Micro optimizations, if works faster than switch

  • And about how much faster? - Bokov Gleb
  • @GurebuBokofu didn’t calculate it personally, I only know that if faster - Silento
  • 3
    I hasten to disagree with you, if there is nothing to be faster than a switch, here it is slower in the absence of optimizations during JIT compilation, but it can be faster only if you select from 2-3 values ​​and again in the absence of optimizations . But nobody turns off optimization, and therefore switches and ifs turn into an identical final set of machine codes. So the choice between a switch and ifes depends only on the preferences of the developer or the codestyle adopted by the team. - xkor
  • I flipped through a bit of English SoF, in the battle of switch vs if all the answers are in favor of the switch. - pavlofff
  • @pavlofff my life will not be the same. - Silento