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