Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Because a <code>switch</code> statement is compiled with two special JVM instructions that are <code>lookupswitch</code> and <code>tableswitch</code>. They are useful when working with a lot of cases but they cause an overhead when you have just few branches.</p> <p>An <code>if/else</code> statement instead is compiled into typical <code>je</code> <code>jne</code> ... chains which are faster but require many more comparisons when used in a long chain of branches.</p> <p>You can see the difference by looking at byte code, in any case I wouldn't worry about these issues, if anything could become a problem then JIT will take care of it.</p> <p>Practical example:</p> <pre><code>switch (i) { case 1: return "Foo"; case 2: return "Baz"; case 3: return "Bar"; default: return null; } </code></pre> <p>is compiled into:</p> <pre><code>L0 LINENUMBER 21 L0 ILOAD 1 TABLESWITCH 1: L1 2: L2 3: L3 default: L4 L1 LINENUMBER 23 L1 FRAME SAME LDC "Foo" ARETURN L2 LINENUMBER 24 L2 FRAME SAME LDC "Baz" ARETURN L3 LINENUMBER 25 L3 FRAME SAME LDC "Bar" ARETURN L4 LINENUMBER 26 L4 FRAME SAME ACONST_NULL ARETURN </code></pre> <p>While</p> <pre><code>if (i == 1) return "Foo"; else if (i == 2) return "Baz"; else if (i == 3) return "Bar"; else return null; </code></pre> <p>is compiled into</p> <pre><code>L0 LINENUMBER 21 L0 ILOAD 1 ICONST_1 IF_ICMPNE L1 L2 LINENUMBER 22 L2 LDC "Foo" ARETURN L1 LINENUMBER 23 L1 FRAME SAME ILOAD 1 ICONST_2 IF_ICMPNE L3 L4 LINENUMBER 24 L4 LDC "Baz" ARETURN L3 LINENUMBER 25 L3 FRAME SAME ILOAD 1 ICONST_3 IF_ICMPNE L5 L6 LINENUMBER 26 L6 LDC "Bar" ARETURN L5 LINENUMBER 28 L5 FRAME SAME ACONST_NULL ARETURN </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload