標籤:
直觀上我感覺 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(); } } }
結果:
case1305297case2285307case3312312case4306310case5294296case6286302case7275291case8276283case9287291case10256271case11256283case12256280case13263287case14262281case15254279case16254281case17250275case18262295case19270282case20254288
Java Try-Catch 對於效能的影響