比较If else 和 try catch 的jvm指令
编码时过度关注某个点性能,有时候整体性能适得其反!关于if else 和 try catch 的性能争辩,看下其JVM指令,再结合各自的使用场景,自己慢慢理解。在此不做评论!
?
另外强调下java的Exception.class!
public class Exception extends Throwable{}
看下Throwable类的结构和设计有好处,便于理解堆栈信息为啥能从Thread的起点到异常点都能打印出来!
?
?
先上Java Code:
?
public class Test{ public void viewException(){ try{ String a = "123_a_"+3; }catch(Exception e){ System.out.println("exception"); } } public void viewThrow(){ try{ int a = 1+888; }catch(Exception e){ throw new RuntimeException(e); } } public int viewIfelse(int num){ if(num==1){ return 1; }else if(num==2){ return 2; }else{ return 0; } }}?
?
再看反编译的JVM 指令:
?
Compiled from "Test.java"public class Test extends java.lang.Object{public Test(); Code: 0: aload_0 1: invokespecial #1; //Method java/lang/Object."<init>":()V 4: returnpublic void viewException(); Code: 0: ldc #2; //String 123_a_3 2: astore_1 3: goto 7 6: astore_1 7: return Exception table: from to target type 0 3 6 Class java/lang/Exceptionpublic void viewThrow(); Code: 0: sipush 889 3: istore_1 4: goto 17 7: astore_1 8: new #4; //class java/lang/RuntimeException 11: dup 12: aload_1 13: invokespecial #5; //Method java/lang/RuntimeException."<init>":(Ljava/lang/Throwable;)V 16: athrow 17: return Exception table: from to target type 0 4 7 Class java/lang/Exceptionpublic int viewIfelse(int); Code: 0: iload_1 1: iconst_1 2: if_icmpne 7 5: iconst_1 6: ireturn 7: iload_1 8: iconst_2 9: if_icmpne 14 12: iconst_2 13: ireturn 14: iconst_0 15: ireturn}??