Stack trace对性能的影响

package ceshi;

public class ExceptionTest {
    public long maxLevel = 20;
    public static void main(String[] args) {
        ExceptionTest test = new ExceptionTest();
        long start = System.currentTimeMillis();
        int count = 100;
        for(int i = 0; i < count; i++){
            try{
                test.doTest(2, 0);
            }catch (Exception e) {
//                e.printStackTrace();
            }
        }
        long diff = System.currentTimeMillis() - start;
        System.out.println(((double)diff/count));
    }
    public void doTest(int i, int level){
        if(level < maxLevel){
            try{
                doTest(i, ++level);
            }catch (Exception e) {
//                e.printStackTrace();
                throw new RuntimeException("UUPS", e);
            }
        }else{
            if(i > 1){
                throw new RuntimeException("Ups");
            }
        }
    }
}

不加注释的情况下平均时间为0.015ms,

加注释的情况下平均时间为38.05ms。

性能倍数是2537倍。

总结:

因为存在性能影响而把异常弃之不用并非良策。异常有助于提供一种一致的方式来解决运行时问题,并且有助于写出干净的代码。但我们应该对代码中抛出的异常数量进行跟踪,它们可能导致显著的性能影响。其次尽管使用异常很有裨益,您也应避免捕获过多的 strack trace。异常应该是为异常的情况而设计的,使用时应该牢记这一原则。

原文地址:https://www.cnblogs.com/tuifeideyouran/p/4587764.html