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