Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Just a random question regarding switch case efficiency in case after case; is the following code (assume pseudo code):

function bool isValid(String myString){
   switch(myString){
   case "stringA":
   case "stringB":
   case "stringC":
      return true;
   default:
      return false;
}

more efficient than this:

function bool isValid(String myString){
   switch(myString){
   case "stringA":
      return true;
   case "stringB":
      return true;
   case "stringC":
      return true;
   default:
      return false;
}

Or is the performance equal? I'm not thinking in a specific language but if needed let's assume it's Java or C (for this case would be needed to use chars instead of strings).

share|improve this question
1  
it will depend from compiler to compiler. However, efficient way (first block on top) is a win-win in maintainability. –  Yusubov Jun 23 '12 at 19:05
1  
It depends on the compiler, did you try profiling for both methods? –  nischayn22 Jun 23 '12 at 19:05
    
Nop I have not tried profiling, but that's a good idea, I will check in netbeans. –  RandomGuy Jun 23 '12 at 19:08
    
Are the strings constants? How about using a HashSet? –  Jon Strayer Jun 23 '12 at 19:50
    
Tried the profiling in the netbeans java ide but the results show that there isn't much difference between each method (in milliseconds), at least with 1000000 calls to each function and with 9 cases in switch. :) Jon Strayer, hashset/hashmap here isn't really needed I believe since it's just 9 cases of strings, and the function will be only called every 5 seconds in the real application. I was just curious if there were any real difference between the two methods. –  RandomGuy Jun 23 '12 at 20:12

3 Answers 3

up vote 5 down vote accepted

It quite depends on compiler. However, as a simple rule, switch is uses JUMP statement (equivalent to GO TO statement) to start from desired point on match condition. So in this case, if multiple condition jumps to same segment or code or different it doesn't add additional conditional check overhead.

One more comparison :

the code if(arg == CASE_1 || arg == CASE_2 || arg == CASE_3) will actually add conditional check with arg == CASE_1 as well as arg == CASE_2 even if arg is actually CASE_3. On the other hand, switch will result in only 1 comparison operation in either way.

In both the above case, i think number of CPU cycles will be identical - because they will amount to 1 condition check and one pop instruction. However, the later will take 2 more redundant instruction in memory. So it is slightly inefficient from code size point of view.

share|improve this answer
    
If I understood correctly the first method only does one condition check even if myString=="stringA" right? case "stringB": case "stringC": are automatically jumped, or are they checked too (in the stringA case)? //Edit: did a quick test in java debugger and seems its does the jump with only one check in stringA case. –  RandomGuy Jun 23 '12 at 22:40
    
@RandomGuy extended my answer. Basically if multiple condition having same routines to execute, doesn't add overhead in switch case at all. –  Dipan Mehta Jun 24 '12 at 3:58

Efficiency shouldn't be your concern here.

Code complexity and maintainability should be your primary concern here.

You should question whether you're operating at the appropriate level of abstraction here.

Emphasis: Why do you feel the need to reach for this hammer (i.e. many case statements in a switch block)?

Recommendation: Take a look at this question on SO.

share|improve this answer
    
I'm using many cases because I need to check 10 strings and return true or false depending if the String being verified is in that "list" or not. –  RandomGuy Jun 23 '12 at 19:22
    
@RandomGuy: In that case, you should reexamine your algorithm. // How big is the list? If it's big, why don't you lean on an index in a database? –  Jim G. Jun 23 '12 at 19:24
    
@RandomGuy: Based on your comment, I strongly advise you to submit your entire problem (or algorithm) to codereview.stackexchange.com . Something just doesn't smell right. –  Jim G. Jun 23 '12 at 19:26
    
It's not that big, it's 9 or 10 strings only. //Edit: Thanks for the advice. I will probably extend the list after but then I will rewrite this without the switch. But when I was writing this code, this efficiency question raised (since it can apply to other codes, even with less cases). –  RandomGuy Jun 23 '12 at 19:27
2  
Not only does this fail to answer the question, it's a bit of a knee-jerk reaction to a switch. Would you have complained at return mystring == "stringa" || mystring == "stringb" etc. (Obviously better laid out than I can in a comment.) –  pdr Jun 23 '12 at 21:02

Layout of case labels is not the bottleneck in this code - string comparison is.

Typically for case labels the compiler is just going to generate a simple jump table and go to the appropriate line of code depending on the value being tested. This is important knowledge - the code that you write in a high-level language often bears very little resemblance to the low-level representation of it that the compiler generates. So you can't make a direct observation about potential performance just by looking at the high-level code.

In the case of C#/Java/whatever, languages which allow strings to appear as case label entries, the rules change. Now the compiler can no longer generate a jump table, it has to do a lot of string comparisons to determine the appropriate branch to follow. And strings are slow.

If you're worried about efficiency of this code, then consider using an enum instead. If you can't (or won't), you can get extra performance out of it by putting the most commonly hit conditions at the top. If this isn't a performance-critical part of your program then do nothing - it's already good enough.

share|improve this answer
    
Good answer. Yes Enums would be a good option if performance was critical or if I had many cases, another option would be use a hash table this if I had many strings I believe like how Jon Strayer mentioned. I was just wondering which one of the two blocks would be the fastest, we can assume it's chars or ints instead of strings for c/c++ for example. –  RandomGuy Jun 23 '12 at 22:21
    
a prefix trie will be able to create a table to jump which can be traversed in O(n) instead of the naive k O(n) comparisons –  ratchet freak Jun 25 '12 at 9:28

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.