Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optimising Java switch statement with many cases?

I am currently using a switch statement to handle types of incoming messages of which there are 20 or so different cases. Some of these cases are orders of magnitude more likely to occur than others.

Is the hotspot compiler able to optimise the order of examining cases to find the correct case to execute or should I structure my code so that the most common cases appear first:

switch(messageType)
{
    case MOST_COMMON:
        // handle it
        break;

...
    case LEAST_COMMON:
        // handle it
        break;
}

All cases are mutually exclusive.

Would I be better off using the strategy pattern and a Map lookup on message type?

Performance is the key concern as I am handling thousands of messages per second and am trying to cut down on object creation and method call overhead.

Many thanks,

Chris

Edit: Thanks for the pointers. messageType is an int with a tight range of values so it looks like it will compile to the "tableswitch" bytecode so no need to reorder the cases.

Relevant part of JVM spec is here http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14942

like image 723
ChrisWhoCodes Avatar asked Nov 04 '11 14:11

ChrisWhoCodes


People also ask

How many cases can a switch statement have in Java?

A statement in the switch block can be labeled with one or more case or default labels.

How many cases should a switch statement have?

ANSI C requires at least 257 case labels be allowed in a switch statement.

How many cases can a switch statement have?

You can use it as many as you like, but it is not a good thing, as your code will become long and boring, this can be avoided by using loops, functions, or several other methods.

Can Switch case have multiple conditions?

The JavaScript switch case is a multiple if else statement. It takes a conditional expression just like an if statement but can have many conditions—or cases—that can match the result of the expression to run different blocks of code.


2 Answers

Unless you are sure that this switch statement is causing you performance problems, then I would suggest that you're optimizing prematurely. Also, check out the accepted answer to this question.

like image 153
Mike Avatar answered Sep 21 '22 17:09

Mike


If the cases are enum values or are densely distributed int values, then mucking with order won't help you once the JIT compiler kicks in to turn it all into a lookup table.

If you're using Java7 string switches or sparsely distributed values, then most common should go first since it turns into a cascading set of if-like test and branch operations.

like image 23
Mike Samuel Avatar answered Sep 19 '22 17:09

Mike Samuel