I am currently using the switch statement to handle incoming message types, of which 20 or more different cases. Some of these cases are an order of magnitude more likely than others.
Is the hotspot compiler able to optimize the order of case checking to find the right case to execute, or should I structure my code so that the first 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 it be better to use a strategy template and map search by message type?
Performance is a key issue as I process thousands of messages per second and try to reduce object creation and method overhead.
Many thanks,
Chris
Edit: Thanks for the pointers. messageType is an int with a limited range of values, so it looks like it will compile to the "tablewitch" bytecode, so there is no need to reorder cases.
The relevant part of the JVM specification is here http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14942
source share