java return throw性能比较

本文通过两个递归函数的性能测试,对比了在Java中使用return语句和抛出异常的成本。实验结果显示,抛出异常的方式比使用return语句慢一倍以上,这为优化代码性能提供了参考。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

-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慢一倍以上

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值