您的位置:首页 > 其它

异常的错误使用导致性能问题

2011-07-11 08:19 309 查看

错误案例

现象描述:
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;
}

测试关注点

压力测试的评估,如果觉得压力测试有问题,及时向开发同学反映。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐