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
A statement in the switch block can be labeled with one or more case or default labels.
ANSI C requires at least 257 case labels be allowed in a switch statement.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With