Optimizing the Java switch statement in many cases?

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

+6
source share
3 answers

If you are not sure if this switch statement causes performance issues, I would suggest that you optimize prematurely. Also, check the accepted answer to this question .

+3
source

If the cases are enum values ​​or are tightly distributed int values, then shutting down with order will not help you after the JIT compiler runs everything to turn it all into a lookup table.

If you use Java7 string variables or rarely distributed values, then the most common should go first, since it turns into a cascading set of if tests and branching operations.

+3
source

The switch statement performs a search to determine which block of code to go to. This is not a series of if / else checks, and the order in which blocks are declared does not affect performance. those. all values ​​of this case are checked equally and immediately.

The pseudocode is the same as (for a small range of int values)

 goto case_label[messageType.ordinal()]; 

For large ranges of values, a different table structure is used. (I guess its hash table)

The CPU can use branch prediction, and if one case is much more common than others, it can optimize execution dynamically.

+1
source

Source: https://habr.com/ru/post/900781/


All Articles