java return throw性能比较

版权声明:本文为qingfeng2556所创,欢迎转载,转载请附加来源。 https://blog.csdn.net/wuhenzhangxing/article/details/83028959
-Xss16m

/**
 * fileName Test
 * author   zhangx
 * date     2018/10/12 16:05
 * description
 */
public class Test {

    public static void main(String[] agrgs){

        int num=100000;
        long start=System.currentTimeMillis();
        System.out.println(test1(num));
        long end=System.currentTimeMillis();
        System.out.println("cost1:"+(end-start)+"ms");

        long start2=System.currentTimeMillis();
        long end2=0;
        try {
            System.out.println(test2(num));
            end2=System.currentTimeMillis();
            System.out.println("cost2:"+(end2-start2)+"ms");
        }catch (Exception e){
            System.out.println(e.getMessage());
        }
        end2=System.currentTimeMillis();
        System.out.println("cost2:"+(end2-start2)+"ms");


    }

    public static String  test1(int num){
        if(num==0){
            return "test";
        }else{
            return test1(--num);
        }
    }

    public static String  test2(int num) {
        if(num==0){
            throw new RuntimeException("test");
        }else{
            return test2(--num);
        }
    }

}
结果:

test
cost1:3ms
test
cost2:8ms

说明throw异常比return慢一倍以上

猜你喜欢

转载自blog.csdn.net/wuhenzhangxing/article/details/83028959
今日推荐