您现在的位置是:首页 > 文章详情

Java 中的 try catch 影响性能吗?

日期:2018-09-16点击:477
前几天在 code review 时发现有一段代码中存在滥用 try catch 的现象。其实这种行为我们也许都经历过,刚参加工作想尽量避免出现崩溃问题,因此在很多地方都想着 try catch 一下。

但实际上这种习惯不仅会让代码很难看,更会影响代码的运行性能。有些人会觉得,不就是一个 try catch 么,怎么会影响性能啊。那就让我们来测试看看吧。

实验

首先,我们看看没有 try-catch 情况下,进行 100 万次加法的耗时:

 
  1. long start = System.nanoTime();

  2. int a = 0;

  3. for (int i = 0; i < 1000000; i++) {

  4. a++;

  5. }

  6. System.out.println(System.nanoTime() - start);

经过5次统计,其平均耗时为:1816048 纳秒,即 1.8 毫秒。

接着,我们来看看在有 try-catch 情况下,进行 100 万次加法的耗时:

 
  1. long start = System.nanoTime();

  2. int a = 0;

  3. for (int i = 0; i < 1000000; i++) {

  4. try {

  5. a++;

  6. } catch (Exception e) {

  7. e.printStackTrace();

  8. }

  9. }

  10. System.out.println(System.nanoTime() - start);

经过5次统计,其平均耗时为: 1928394 纳秒,即 1.9 毫秒。

我们再来看看,如果 try-catch 抛出异常,进行 100 万次加法的耗时:

 
  1. long start = System.nanoTime();

  2. int a = 0;

  3. for (int i = 0; i < 1000000; i++) {

  4. try {

  5. a++;

  6. throw new Exception();

  7. } catch (Exception e) {

  8. e.printStackTrace();

  9. }

  10. }

  11. System.out.println(System.nanoTime() - start);

经过 5 次统计,其平均耗时为:780950471 纳秒,即 780 毫秒。

经过上面三次统计,我们可以看到在没有 try catch 时,耗时 1.8 毫秒。在有 try catch 但是没有抛出异常,耗时 1.9 毫秒。在有抛出异常,耗时 780 毫秒。我们能得出一个结论:如果 try catch 没有抛出异常,那么其对性能几乎没有影响。但如果抛出异常,那对程序将造成几百倍的性能影响。

结论

虽然在没有抛出异常时,try catch 几乎没有性能影响。但是一旦抛出异常,那么其对性能的影响将是巨大的。因此我们在实际编程的时候,需要特别注意 try catch 语句的使用,不在没有必要的地方过多使用。


原文发布时间为:2018-09-16
本文作者:Java技术驿站
本文来自云栖社区合作伙伴“Java技术驿站”,了解相关信息可以关注“Java技术驿站”。

原文链接:https://yq.aliyun.com/articles/640811
关注公众号

低调大师中文资讯倾力打造互联网数据资讯、行业资源、电子商务、移动互联网、网络营销平台。

持续更新报道IT业界、互联网、市场资讯、驱动更新,是最及时权威的产业资讯及硬件资讯报道平台。

转载内容版权归作者及来源网站所有,本站原创内容转载请注明来源。

文章评论

共有0条评论来说两句吧...

文章二维码

扫描即可查看该文章

点击排行

推荐阅读

最新文章