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; } }
Erwin Bolwidt Mar 01 '14 at 6:01 2014-03-01 06:01
source share