Java Try-Catch 对于性能的影响

直观上我感觉 try catch 对于程序有性能上的影响,但是以下的实验可以说明部分情况下try - catch 只是逻辑上的影响,与性能无太大的拖累

  public static void main(String[] args) throws Exception {

        int n = 10000;

        for (int j = 0; j < 20; j++) {
            System.out.println("case" + (j + 1));
            long start = System.currentTimeMillis();
            for (int i = 0; i < n; i++) {
                try {
                    testProcess();
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
            System.out.println(System.currentTimeMillis() - start);

            start = System.currentTimeMillis();
            for (int i = 0; i < n; i++) {

                testProcess();

            }
            System.out.println(System.currentTimeMillis() - start);
        }

    }

    public static void testProcess() {
        int c = 1;
        for (int i = 1; i < 10000; i++) {
            c *= i;
            if (c % 2 == 0) {
                c += i;
            }
            if (i == 0) {
                throw new RuntimeException();
            }
        }
    }

 

结果:

case1
305
297
case2
285
307
case3
312
312
case4
306
310
case5
294
296
case6
286
302
case7
275
291
case8
276
283
case9
287
291
case10
256
271
case11
256
283
case12
256
280
case13
263
287
case14
262
281
case15
254
279
case16
254
281
case17
250
275
case18
262
295
case19
270
282
case20
254
288

 

转载于:https://www.cnblogs.com/fantasy-es/p/4612507.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值