Java异常的性能分析(二)

2014-11-24 00:41:30 · 作者: · 浏览: 3
t is not numeric
}
else if ( c == '+' )
{
if ( i == 0 )
sign = 1; //sign at first position
else
return str; //otherwise it is not numeric
}
else //non-numeric
return str;
}
//cast to int if value is in int range
if ( res < Integer.MAX_VALUE )
return ( int ) res * sign;
//otherwise return Long
return res * sign;
}


很惊讶吧,新的方法解析数字比JDK的实现快多了!很大一个原因是因为JDK在解析的最后,调用了一个支持的解析方法,像这样:

public static int parseInt( String s, int radix ) throws NumberFormatException


新的方法和旧的相比(注意方法调用的次数――对于非数字串pack只调用了1百万次,而别的情况能调用到千万级别):


Pack: Made 100.000.000 iterations for string '12345' : time = 12.145 sec
Pack: Made 1.000.000 iterations for string '12345a' : time = 23.248 sec
strToObject: Made 100.000.000 iterations for string '12345' : time = 6.311 sec
strToObject: Made 100.000.000 iterations for string '12345a' : time = 5.807 sec



总结



千万不要把异常当成返回码一样用,或者当作可能发生的事件(尤其是和IO无关的方法)往外抛。抛异常的代价太昂贵了,对于一般的方法,至少要慢百倍以上。

如果你每条数据都需要解析,又经常会出现非数值串的时候,尽量不要用Number子类型的parse*/valueOf这些方法。为了性能考虑,你应当手动解析它们。


原创文章转载请注明出处:http://it.deepinmind.com

英文原文链接