2026/3/25 1:36:14
网站建设
项目流程
python基础教程百度网盘,深圳市seo网站设计,专业模板网站制作多少钱,租房子网站怎么做Java 进阶异常影响性能吗 catch 中不做任何事情catch 中输出异常到日志catch 中获取异常栈总结
Java 进阶#xff1a;异常影响性能吗#xff1f;
曾经在给一个业务系统增加限流功能#xff0c;使用的限流组件在流量超过阈值时#xff0c;会直接抛异常#xff0c;异常导…Java 进阶异常影响性能吗catch 中不做任何事情catch 中输出异常到日志catch 中获取异常栈总结Java 进阶异常影响性能吗曾经在给一个业务系统增加限流功能使用的限流组件在流量超过阈值时会直接抛异常异常导致 CPU 占用率飙升。第一次遇到这样的情况让我们不得不思考异常怎么会对性能造成这么大的影响下面我们写几个测试程序观察一下。catch 中不做任何事情public class ExceptionTest { public static void main(String[] args) { doExTest(); doExTest(); } private static void doExTest() { long start System.nanoTime(); for (int i0; i100000; i) { try { throw new RuntimeException( Math.random()); } catch (Exception e) { } } System.out.println(time: (System.nanoTime() - start)); } }测试结果如下time: 365218274time: 224583244第一次 doExTest 只是起到预热的作用我们以第二次 doExTest 的时间为准。10 万次请求平均每次请求耗时 2245 纳秒也就是 0.002 毫秒速度还是很快的。catch 中输出异常到日志public class ExceptionTest { private static final Logger logger LoggerFactory.getLogger(ExceptionTest.class); public static void main(String[] args) { doExTest(); doExTest(); } private static void doExTest() { long start System.nanoTime(); for (int i0; i100000; i) { try { throw new RuntimeException( Math.random()); } catch (Exception e) { logger.error(fuck, e); } } System.out.println(time: (System.nanoTime() - start)); } }测试结果如下time: 13454674590time: 989178045010 万次请求平均每次请求耗时 98917 纳秒大约 0.1 毫秒比“不输出异常”的时候慢了 50 倍。输出日志如此耗费性能那么 logger.error 这一句做了什么事儿呢1. 根据过滤规则判断是否要输出日志2. 获取异常堆栈3. 拼接日志字符串输出日志到文件获取异常堆栈主要调用的如下方法下面我们写程序不输出日志到文件测试只读取异常栈的性能public class Throwable implements Serializable { public StackTraceElement[] getStackTrace() { return getOurStackTrace().clone(); } private synchronized StackTraceElement[] getOurStackTrace() { // Initialize stack trace field with information from // backtrace if this is the first call to this method if (stackTrace UNASSIGNED_STACK || (stackTrace null backtrace ! null) /* Out of protocol state */) { int depth getStackTraceDepth(); stackTrace new StackTraceElement[depth]; for (int i0; i depth; i) stackTrace[i] getStackTraceElement(i); } else if (stackTrace null) { return UNASSIGNED_STACK; } return stackTrace; } }catch 中获取异常栈public class ExceptionTest { public static void main(String[] args) { doExTest(); doExTest(); } private static void doExTest() { long start System.nanoTime(); for (int i0; i100000; i) { try { throw new RuntimeException( Math.random()); } catch (Exception e) { StackTraceElement[] stackTrace e.getStackTrace(); } } System.out.println(time: (System.nanoTime() - start)); } }测试结果如下time: 1559107012time: 79537677510 万次请求平均每次请求耗时 7953 纳秒大约 0.008 毫秒比“不输出异常”的时候慢了 4 倍。这么看获取堆栈耗时并不多耗时主要在输出日志到文件中。总结处理异常的几个步骤里对性能的耗费从大到小依次为输出到日志、获取异常堆栈、创建并 catch 异常。