Using a switch statement is faster than equals (but only noticeably when there are more than just a few strings) because it first uses the hashCode
of the string that switch
on to determine the subset of the strings that could possibly match. If more than one string in the case labels has the same hashCode, the JVM will perform sequential calls to equals
and even if there is only one string in the case labels that a hashCode, the JVM needs to call equals
to confirm that the string in the case label is really equal to the one in the switch expression.
The runtime performance of a switch on String objects is comparable to a lookup in a 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;
}
}
Is internally compiled to and executed like this piece of code:
(not literally, but if you decompile both pieces of code you see that the exact same sequence of actions occurs)
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;
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…