錯誤案例
現象描述:
String strValue = (String) source; try { return new Integer(strValue); } catch (Exception e) { try { return new Integer(strValue.trim()); } catch (Exception ex) { return new Integer(0); } }
粗體標出的代碼是存在性能問題的。
錯誤分析
構造一個Exception性能開銷比較大,異常拋出首先需要創建一個新的對象,其異常Throwable類中的構造函數調用名爲fillInStackTrace()的本地方法,這個方法加鎖以實現收集跟蹤信息。
正確用法
正確代碼:異常應當僅用於有錯誤發生時,而不要控制業務流程。正確使用exception,在exception裏面主要做些資源清理或者日誌記錄的操作。
static Integer ZERO_INTEGER = Integer.valueOf(0); public Object convert(Object source) { String strValue = (String) source; if (strValue == null) { return ZERO_INTEGER; } strValue = strValue.trim(); if (strValue.length() == 0) { return ZERO_INTEGER; } Integer ret = null; try { ret = new Integer(strValue); } catch (NumberFormatException e) { ret = ZERO_INTEGER; } return ret; }
測試關注點
壓力測試的評估,如果覺得壓力測試有問題,及時向開發同學反映。