近期,在与同事讨论一些编程风格的时候出现一些分歧。比如说,将一个字符串转成数字。我认为应该判断字符串格式是否正确然后再转成数字,同事则认为直接调用Integer.parseInt()然后再异常处理。就此问题做出如下测试。
public class TestDependException { public static void main(String[] args) { test(); // System.out.println(common("123")); } /* * 结论:当字符串不会产生异常时,dependException有压倒性的优势。 运行10次取平均值(85 - 3) * 当存在异常时并且循环次数超过40000时,在速度方便常规方法才显露出优势。 循环400次(12 - 4) 循环4W次(84 - 86) * 占用内存等其他方面没有进行考虑 */ public static void test() { int times = 40000; String commonStr = "1234"; String exceptionStr = "12a34"; String currentStr = exceptionStr; long startTime = System.currentTimeMillis(); for(int i = 0; i < times; i++) { common(currentStr); } long centerTime = System.currentTimeMillis(); for(int i = 0; i < times; i++) { dependException(currentStr); } long endTime = System.currentTimeMillis(); System.out.println((centerTime - startTime) + " - " + (endTime - centerTime)); } public static int common(String str) { if(str.matches("(\d*)|(-\d++)")) { return Integer.parseInt(str); } return 0; } public static int dependException(String str) { try { return Integer.parseInt(str); } catch (NumberFormatException e) { return 0; } } }
从测试结果不难看出,依赖异常编程已经胜出(在普通的应用中很少会出现异常,且异常对象也会很快被垃圾回收器回收,因此我认为在内存占用上也不算很明显的劣势),但是总感觉这种处理问题的方式不是太好(也许是由于C的遗传,C没有异常处理)。请各位大神讨论一下,如何进行编程才是最佳的方式,并附上理由,谢谢。