try catch 和 if else 性能比较

2020-05-12  本文已影响0人  木木呦

今天发现一段代码,是用try catch 代替了if else做判断。在catch中做put("key", " ")操作,之前看到说try catch会存在性能问题,然后百度上又有人说,只要不调用printStackTrace()方法,就不会存在,所以记录下到底是不是真的。

public class TestDemo {

    public static void eachValue(String[] strArray) {
        Map<String, Object> hashMap = new HashMap<>();

        int length = strArray.length;
        for (int i = 0; i < length; i++) {
            hashMap.put("" + i, strArray[i]);
        }

        for (int j = length; j < 10000; j++) {

/*            if (j < (strArray.length-1)){
                hashMap.put(""+j, strArray[j]);
            }else {
                hashMap.put(""+j, "");
            }*/

            try {
                hashMap.put("" + j, strArray[j]);
            } catch (Exception e) {
                hashMap.put("" + j, "");
            }
        }

    }

    public static void main(String[] args) {
        String[] str = {"小米", "华为", "中兴"};

        // 运行6次
        for (int i = 0; i < 6; i++) {
            long begin = System.nanoTime();
            TestDemo.eachValue(str);
            long end = System.nanoTime();
            System.out.println("纳秒:" + (end - begin));
        }

    }

}

执行结果

try catch 结果
if else 结果

改为指定类型异常ArrayIndexOutOfBoundsException


ArrayIndexOutOfBoundsException
try catch结果

总结

try catch的性能确实要比if else的性能低,只要用了try catch性能必然受到一点影响。可能有人说,实际项目哪有这么多次的调用,可能也就6层以下,那么可以尝试把循环次数改为6,数据显示,依旧是if else快的,这里就不截图了。

上一篇 下一篇

猜你喜欢

热点阅读