• [讨论] 传统编程与依赖异常编程


    近期,在与同事讨论一些编程风格的时候出现一些分歧。比如说,将一个字符串转成数字。我认为应该判断字符串格式是否正确然后再转成数字,同事则认为直接调用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没有异常处理)。请各位大神讨论一下,如何进行编程才是最佳的方式,并附上理由,谢谢。

  • 相关阅读:
    python simplejson and json 使用及区别
    python 网页抓取并保存图片
    word2vec剖析,资料整理备存
    centos 安装LAMP环境后装phpmyadmin
    centos 安装卸载软件命令 & yum安装LAMP环境
    Ubuntu终端快捷键使用
    Ubuntu终端文件的压缩和解压缩命令
    文本预处理去除标点符号
    朴素贝叶斯分类器的应用
    Win32环境下代码注入与API钩子的实现(转)
  • 原文地址:https://www.cnblogs.com/hzm112567/p/3331653.html
Copyright © 2020-2023  润新知