用多种情况优化 Java switch 语句?

2022-01-19 00:00:00 performance switch-statement java

我目前正在使用 switch 语句来处理传入消息的类型,其中有 20 种左右不同的情况.其中一些情况发生的可能性比其他情况高出几个数量级.

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;
}

所有情况都是互斥的.

使用策略模式和消息类型的地图查找会更好吗?

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.

非常感谢,

克里斯

感谢您的指点.messageType 是一个具有严格值范围的 int,因此看起来它将编译为tableswitch"字节码,因此无需重新排序案例.

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.

JVM 规范的相关部分在这里 http://java.sun.com/docs/books/jvms/second_edition/html/Compiling.doc.html#14942

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

推荐答案

除非您确定此 switch 语句会导致性能问题,否则我建议您过早地进行优化.另外,请查看 接受的回答这个问题.

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.

相关文章