Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does switch case order affect speed? [duplicate]

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.

For illustration:

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);     } 
like image 559
MightyPork Avatar asked Apr 21 '14 19:04

MightyPork


Video Answer


1 Answers

Reordering a switch statement does not have any effect.

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.

like image 186
Louis Wasserman Avatar answered Sep 25 '22 04:09

Louis Wasserman