1

I would like to know whether order of values in Switch matters according to its type e.g. if I have big switch case with boolean, short, long, float, etc. - (if BOOLEAN is faster than NULL , will it be faster to put case which can return NULL or is it faster to put case, which will return BOOLEAN?

So I have two questions:

  1. Is order in Switch case held? (from up to down?)
  2. Due to performance/speed - does the order of values in case matter?

code snippet:

switch (user){
        case Test.CHAR:
            return readChar();

        case Test.SHORT:
            return readShort();

        case Test.BOOLEAN:
            return readBoolean();

        case Test.BYTE:
            return readByte();

        case Test.INT:
            return readInt();

        case Test.LONG:
            return readLong();

        case Test.STRING:
            return readString();
}
DRastislav
  • 1,892
  • 3
  • 26
  • 40
  • 5
    Don't worry about it. Just code the order you have now, then use a profiler to demonstrate if this is the real performance bottleneck. Let the JVM optimize this and focus on optimizing your algorithms. – Luiggi Mendoza Dec 15 '14 at 17:26
  • 2
    I'm adding this comment as clarification, but I assume the order is held from top down isn't it? I thought that's the whole reason we add 'break' statements, because otherwise it will cascade down the list. – AdamMc331 Dec 15 '14 at 17:30
  • 1
    See http://stackoverflow.com/questions/8011020/optimising-java-switch-statement-with-many-cases – lbalazscs Dec 15 '14 at 17:37
  • I don't understand the question. The `switch` statement only works on an `int` or a shorter integer type, or `String`, or an enum type; it doesn't work on `boolean`, `long`, or `float`. Could you give a shortened example of what kind of `switch` statement you're thinking about? – ajb Dec 15 '14 at 17:51
  • Hello @ajb - i thought return values in case ( return boolean, short, long etc.) – DRastislav Dec 15 '14 at 17:58
  • You mean you have a `switch` statement that has `return` statements in the body? I don't see how there's any relation between the order of the `cases` and what gets returned. The `switch` statement selects one `case` to execute, then it jumps there; `return` statements in other cases aren't going to have any effect on anything. Perhaps you should still include a code example, since I am having trouble seeing how this question makes sense. – ajb Dec 15 '14 at 18:02
  • OK, thanks for the code. When the `switch` is executed, the program looks at `user`, jumps to the correct `case`, calls the method at that `case`, and returns the result. The code in the other cases has no impact, since those methods won't be called. I'm not sure why you think the order would possibly make a difference--what were you thinking the program would do? – ajb Dec 15 '14 at 18:13

0 Answers0