Does the box order justify speed?

I tried to do this google but no luck.

I have a very large switch, and some cases are obviously more common than others.

So, I would like to know if the order is really followed, and the "upper" cases are checked to the "lower", so they are evaluated faster.

I would like to keep my order, but if it hurts the speed, then reordering the branches would be a good idea.

To illustrate:

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); } 
+74
java switch-statement
Apr 21 '14 at 19:36
source share
1 answer

Reordering the switch statement has no effect.

Looking at the Java bytecode specification, a switch can be compiled into a lookupswitch or tableswitch by including int . A lookupswitch always compiled with possible values ​​in sorted order, so reordering constants in the code does not matter, and tableswitch just has an array of possible jumps relative to a given offset, so it also 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.

+106
Apr 21 '14 at 19:50
source share



All Articles