Java到底能不能使用异常来控制流程?


前言

我们经常在很多项目里面看到用异常来处理业务逻辑,发现不符合预期直接抛出异常,然后在最外面捕获异常统一处理,这样使用非常方便。

但是又有很多文章写着异常处理性能,所以不建议使用异常来做流程控制。甚至在阿里巴巴开发手册里面明确说明了,不要用来做流程控制。

Java到底能不能使用异常来控制流程?

 

那么问题来了:

究竟能不能用异常来做流程控制?效率低是低多少?看完这一篇文章你就知道了。

开始测试

先做最简单的测试

我们循环10万次,然后栈有5层,然后输出返回结果。

 private static final int RUN_COUNT = 10 * 10000;      /**      * 测试异常耗时      * 输出异常堆栈&信息      */     @Test     public void printStack() {         long start1 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             log.info(Storey1.test());         }          long start2 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             try {                 Storey1.testException();             } catch (Exception e) {                 log.info(e.getMessage(), e);             }         }         long end = System.currentTimeMillis();         log.info("普通返回耗时:{},异常返回耗时:{}", start2 - start1, end - start1);     }     public static class Storey1 {         public static String test() {             return Storey2.test();         }          public static String testException() {             return Storey2.testException();         }     }      public static class Storey2 {         public static String test() {             return Storey3.test();         }          public static String testException() {             return Storey3.testException();         }     }      public static class Storey3 {         public static String test() {             return Storey4.test();         }          public static String testException() {             return Storey4.testException();         }     }      public static class Storey4 {         public static String test() {             return Storey5.test();         }          public static String testException() {             return Storey5.testException();         }     }      public static class Storey5 {         public static String test() {             return Integer.toString(count++);         }          public static String testException() {             throw new CustomException(Integer.toString(count++));         }     }       public static class CustomException extends RuntimeException {          public CustomException(String message) {             super(message);         }      }

结果差别很大,普通返回只要2137毫秒,而异常却要75026毫秒,几十倍的差距。

 15:07:59.648 [main] INFO com.alibaba.easytools.test.temp.exception.ExceptionTest - 普通返回耗时:2137,异常返回耗时:75026

不输出堆栈信息

聪明的同学不难发现,上面有个变量没控制住,就是使用异常的情况下,输出了堆栈信息,那我们关闭堆栈输出试试。会不会是输出的堆栈信息导致的慢呢?

   /**      * 测试异常耗时      * 仅仅输出信息      */     @Test     public void print() {         long start1 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             log.info(Storey1.test());         }          long start2 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             try {                 Storey1.testException();             } catch (Exception e) {                 log.info(e.getMessage());             }         }         long end = System.currentTimeMillis();         log.info("普通返回耗时:{},异常返回耗时:{}", start2 - start1, end - start1);     }

结果发现普通返回是2053毫秒,而异常却要4380毫秒,发现差距瞬间变小了。

 15:43:54.260 [main] INFO com.alibaba.easytools.test.temp.exception.ExceptionTest - 普通返回耗时:2053,异常返回耗时:4380

不输出任何信息

显然我们发现,关闭了日志输出对执行时间影像很大,那我们关闭了日志输出会有什么效果了呢?

     /**      * 测试异常耗时      * 不输出信息      */     @Test     public void noPrint() {         long start1 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             Storey1.test();         }          long start2 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             try {                 Storey1.testException();             } catch (Exception e) {             }         }         long end = System.currentTimeMillis();         log.info("普通返回耗时:{},异常返回耗时:{}", start2 - start1, end - start1);     }

结果发现普通返回是58毫秒,而异常却要719毫秒,看来性能实际差距就是十几倍。

 15:47:55.901 [main] INFO com.alibaba.easytools.test.temp.exception.ExceptionTest - 普通返回耗时:58,异常返回耗时:719

关闭堆栈

在处理异常的时候,很多时间在封装异常堆栈,那有没有办法可以不要封装呢?

仔细研究异常类发现,异常类有个参数`writableStackTrace` 可以让异常不去封装堆栈信息。

 public class RuntimeException extends Exception {      /**      * Constructs a new runtime exception with the specified detail      * message, cause, suppression enabled or disabled, and writable      * stack trace enabled or disabled.      *      * @param  message the detail message.      * @param cause the cause.  (A {@code null} value is permitted,      * and indicates that the cause is nonexistent or unknown.)      * @param enableSuppression whether or not suppression is enabled      *                          or disabled      * @param writableStackTrace whether or not the stack trace should      *                           be writable      *      * @since 1.7      */     protected RuntimeException(String message, Throwable cause,                                boolean enableSuppression,                                boolean writableStackTrace) {         super(message, cause, enableSuppression, writableStackTrace);     } }

我们把抛异常的时候不去封装异常信息

     /**      * 测试异常耗时      * 关闭堆栈 并且不打印      */     @Test     public void noPrintCloseStackTrace() {         long start1 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             Storey1.test();         }          long start2 = System.currentTimeMillis();         for (int i = 0; i < RUN_COUNT; i++) {             try {                 Storey1.testException();             } catch (Exception e) {             }         }         long end = System.currentTimeMillis();         log.info("普通返回耗时:{},异常返回耗时:{}", start2 - start1, end - start1);     }      public static class Storey5 {         public static String test() {             return Integer.toString(count++);         }          public static String testException() {            throw new CustomException(Integer.toString(count++), null, false, false);         }     }      public static class CustomException extends RuntimeException {          public CustomException(String message) {             super(message);         }          public CustomException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) {             super(message, cause, enableSuppression, writableStackTrace);         }     }

结果发现普通返回是31毫秒,而异常却要62毫秒,差距也没有想象中的大了。差不多是2倍左右。

 15:54:26.984 [main] INFO com.alibaba.easytools.test.temp.exception.ExceptionTest - 普通返回耗时:31,异常返回耗时:62

最终结果

我们来看下最终对比结论

 

普通

异常

普通输出日志,异常输出堆栈

2137

75026

普通输出日志,异常仅输出日志

2053

4380

都不输出日志

58

719

关闭堆栈

31

62

结论

所以我们可以总结出以下结论

  • 日志输出堆栈非常耗时
  • 哪怕日志只是输出业务逻辑,耗时和业务处理也不是一个时间维度的
  • 排出日志影响,封装堆栈非常耗时
  • 关闭堆栈以后耗时相差不大,大概1万次相差3毫秒

三种方式优缺点总结下:

 

优点

缺点

普通

  • 最快速
  • 嵌套深了,或者有返回值的情况下代码会比较丑陋
  • 如果打印了请求日志,多个地方返回相同值,不好排查

关闭堆栈的异常

  • 相对速度还行
  • 代码相对书写比较方便
  • 有时候不打印堆栈多个地方返回相同值,不好排查

不关闭堆栈的异常

  • 代码相对书写比较方便
  • 能打印整个堆栈信息,非常容易定位问题
  • 速度慢

如果我们的并发没有大到必须关闭日志这种情况下,实际上来说异常来控制流程问题不大,影响微乎其微,所以还是怎么方便怎么来。

当然如果项目并发超级高,高到单机1万次请求要省3毫秒的情况下,建议还是用返回去控制业务流程。

本文收集自互联网,如果发现有涉嫌侵权或违法违规的内容,请联系6532516@qq.com以便进行及时清除
分享到