0

So i have an Onclick listener that's listening to about 20 ids (view.getId() >> switch R.id....). Does me not putting break statements at each case affect performance?

thanks for your help.

Makoto
  • 104,088
  • 27
  • 192
  • 230
micnubinub
  • 116
  • 1
  • 8

2 Answers2

1

Not putting break would decrease performance if anything, as instead of quitting the switch block, your app would have to go through all other case statements.

Szymon
  • 42,577
  • 16
  • 96
  • 114
  • thanks for your answer. just discovered it was a good idea the hard way, my app was force closing cause it was trying to do an xml rotaion animation on a view that wasn't visible at the time(view is on a dialog). **Can't answer my own question cause i have a student reputation. – micnubinub Jan 29 '14 at 01:58
1

I know you've already answered your question, but I'll just post this comment in case anyone is particularly interested in the answer to your title. In general switch statements are highly efficient. You can find a lot of details online regarding the performance comparisons of different java operations, but for large comparison sets, switch statements allow for direct indexing in the best case, through to O(log2(n)), where as if statements are on average n/2 and n on worst case.

Additionally, switch statements are much more maintainable than a long set of if-else statements.

So in general: If you are comparing integers and have more than 2 comparisons, it's usually best to use a switch statement, otherwise use an if-else.

For more details: What is the relative performance difference of if/else versus switch statement in Java?

Community
  • 1
  • 1
TheIT
  • 11,919
  • 4
  • 64
  • 56