Does switch case order affect speed?(开关盒顺序会影响速度吗?)
问题描述
我试过用谷歌搜索,但没有运气.
I've tried to google this, but had no luck.
我有一个很大的转变,有些情况显然比其他情况更常见.
I have a very big switch, and some cases are obviously more common than others.
所以我想知道订单是否真的保持原样,并且上"案例在下"之前得到测试,因此评估速度更快.
So I would like to know if the order is really held as it is and the "upper" cases get tested before the "lower", therefore being evaluated faster.
我想保持我的订单,但如果它影响速度,那么重新排序分支将是一个好主意.
I'd like to keep my order, but if it hurts speed, then reordering the branches would be a good idea.
为了说明:
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 语句没有任何效果.
Reordering a switch statement does not have any effect.
查看 Java 字节码规范,switch 可以编译为 lookupswitch 或 tableswitch 指令,打开 >int.lookupswitch 总是以排序顺序使用可能的值进行编译,因此重新排序代码中的常量无关紧要,并且 tableswitch 只是有一个可能的相对跳转数组到指定的偏移量,因此它也从不关心原始顺序.
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.
参见 http:///docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.lookupswitch 和 http://docs.oracle.com/javase/specs/jvms/se7/html/jvms-6.html#jvms-6.5.tableswitch 了解详情.
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.
这篇关于开关盒顺序会影响速度吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:开关盒顺序会影响速度吗?
基础教程推荐
- 不推荐使用 Api 注释的描述 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 大摇大摆的枚举 2022-01-01
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
