开关机箱顺序会影响速度吗?

2022-08-31 12:16:34

我试图谷歌这个,但没有运气。

我有一个非常大的开关,有些情况显然比其他情况更常见

因此,我想知道订单是否真的保持原样,并且“较高”情况在“较低”情况之前进行测试,因此可以更快地进行评估。

我想保留我的订单,但如果它损害了速度,那么重新排序分支将是一个好主意。

举例说明:

switch (mark) {
        case Ion.NULL:
            return null;

        case Ion.BOOLEAN:
            return readBoolean();

        case Ion.BYTE:
            return readByte();

        case Ion.CHAR:
            return readChar();

        case Ion.SHORT:
            return readShort();

        case Ion.INT:
            return readInt();

        case Ion.LONG:
            return readLong();

        case Ion.FLOAT:
            return readFloat();

        case Ion.DOUBLE:
            return readDouble();

        case Ion.STRING:
            return readString();

        case Ion.BOOLEAN_ARRAY:
            return readBooleans();

        case Ion.BYTE_ARRAY:
            return readBytes();

        case Ion.CHAR_ARRAY:
            return readChars();

        case Ion.SHORT_ARRAY:
            return readShorts();

        case Ion.INT_ARRAY:
            return readInts();

        case Ion.LONG_ARRAY:
            return readLongs();

        case Ion.FLOAT_ARRAY:
            return readFloats();

        case Ion.DOUBLE_ARRAY:
            return readDoubles();

        case Ion.STRING_ARRAY:
            return readStrings();

        default:
            throw new CorruptedDataException("Invalid mark: " + mark);
    }

答案 1

对 switch 语句重新排序不会产生任何影响。

查看 Java 字节码规范,可以将 a 编译为 a 或指令,打开 .A 总是按排序顺序使用可能的值进行编译,因此对代码中的常量进行重新排序将无关紧要,并且 a just 具有相对于指定偏移量的可能跳转数组,因此它也从不关心原始顺序。switchlookupswitchtableswitchintlookupswitchtableswitch

有关详细信息,请参阅 http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.lookupswitchhttp://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.tableswitch


答案 2