How is the line in the switch statement more efficient than the corresponding if-else statement?

Java documentation says

The Java compiler generates a generally more efficient bytecode from switch statements that use String objects than from chained if-then-else statements.

AFAIK even String in the switch uses .equals() internally case-sensitive manner. So what is the effectiveness in this context. Faster compilation? Less bytecodes? better performance?

+41
java string switch-statement if-statement
Mar 01 '14 at 5:47
source share
3 answers

Using the switch statement is faster than equals (but noticeable only if there are several lines), because it first uses hashCode lines, in which switch to identify a subset of lines that might possibly match. If more than one line in the case labels has the same hash code, the JVM will make consecutive equals calls, and even if there is only one line in the case labels that has hashCode, the JVM needs to call equals to confirm that the line in the case label really equal to what is in the switch statement.

The performance of starting a switch on String objects is comparable to a search in HashMap .

This piece of code:

 public static void main(String[] args) { String s = "Bar"; switch (s) { case "Foo": System.out.println("Foo match"); break; case "Bar": System.out.println("Bar match"); break; } } 

Internally compiled and executed as this piece of code:

(not literally, but if you decompile both parts of the code, you will see that the exact sequence of actions is happening)

 final static int FOO_HASHCODE = 70822; // "Foo".hashCode(); final static int BAR_HASHCODE = 66547; // "Bar".hashCode(); public static void main(String[] args) { String s = "Bar"; switch (s.hashCode()) { case FOO_HASHCODE: if (s.equals("Foo")) System.out.println("Foo match"); break; case BAR_HASHCODE: if (s.equals("Bar")) System.out.println("Bar match"); break; } } 
+53
Mar 01 '14 at 6:01
source share

In general , switch statements are better because they are (fluent) O(1) , and the if-else chain is O(n)

The presence of conditions n can lead to comparison with n comparison using the if-else chain.

The switch statement can "jump" directly to the corresponding condition (for example, to the map) or to the default case, making it O(1) .

+16
Mar 01 '14 at 5:56
source share

This is a bytecode snippet generated from the example in the docs:

  INVOKEVIRTUAL java/lang/String.hashCode ()I LOOKUPSWITCH -2049557543: L2 -1984635600: L3 -1807319568: L4 

using LOOKUPSWITCH has better performance than if-else logic

+6
Mar 01 '14 at 5:52
source share



All Articles