java - How is String in switch statement more efficient than corresponding if-else statement? -


java documentation says

the java compiler generates more efficient bytecode switch statements use string objects chained if-then-else statements.

afaik string in switch uses .equals() internally in case sensitive manner. efficiency mean in context. faster compilation? less bytecodes ? better performance?

using switch statement faster equals (but noticeably when there more few strings) because first uses hashcode of string switch on determine subset of strings possibly match. if more 1 string in case labels has same hashcode, jvm perform sequential calls equals , if there 1 string in case labels hashcode, jvm needs call equals confirm string in case label equal 1 in switch expression.

the runtime performance of switch on string objects comparable lookup 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;     } } 

is internally compiled , executed piece of code:

(not literally, if decompile both pieces of code see 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;     } } 

Comments

Popular posts from this blog

python - Operations inside variables -

Generic Map Parameter java -

arrays - What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it? -