developer tip

스위치 케이스 순서가 속도에 영향을 줍니까?

optionbox 2020. 10. 8. 07:55
반응형

스위치 케이스 순서가 속도에 영향을 줍니까?


이 질문에 이미 답변이 있습니다.

나는 이것을 구글 시도했지만 운이 없었다.

나는 매우 큰 스위치를 가지고 있으며 어떤 경우는 다른 것보다 분명히 더 일반적 입니다.

따라서 주문이 실제로 그대로 유지되고 "상위"케이스가 "하한"보다 먼저 테스트되므로 더 빨리 평가되는지 알고 싶습니다.

주문을 유지하고 싶지만 속도가 나빠지면 가지를 재정렬하는 것이 좋습니다.

예시 :

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

switch 문을 다시 정렬해도 효과가 없습니다.

Looking at the Java bytecode spec, a switch can either be compiled to a lookupswitch or a tableswitch instruction, switching on an int. A lookupswitch is always compiled with the possible values in sorted order, so reordering the constants in the code will never matter, and a tableswitch just has an array of the possible jumps relative to a specified offset, so it, too, never cares about the original order.

See http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.lookupswitch and http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.tableswitch for details.

참고URL : https://stackoverflow.com/questions/23204580/does-switch-case-order-affect-speed

반응형