Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Does the exception in Java affect the efficiency of the program?

2025-03-05 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/03 Report--

本篇内容介绍了"Java中的异常对程序效率有没有影响"的有关知识,在实际案例的操作过程中,不少人都会遇到这样的困境,接下来就让小编带领大家学习一下如何处理这些情况吧!希望大家仔细阅读,能够学有所成!

当异常没有发生时,没有影响。

其实从异常实现的角度来看,在throw语句处,跳转到异常的处理代码,不同的异常处理,应该类似C++中的虚函数表一样的数构结构(待考证)。

所以如果没有抛出异常,那和普通的代码完全一样。至于在抛出异常时要处理的开销和不使用异常,用返回码等来判断不同的错误,不仅代码复杂,而且也一样要有处理的开销。

测试代码:

import java.util.Date; public class Test { long size = 1000000000L; public static void main(String[] args) { Test t = new Test(); t.test1(); t.test1(); t.test1(); t.test2(); t.test2(); t.test2(); t.test1(); t.test1(); t.test1(); t.test2(); t.test2(); t.test2(); } long func1(long i) throws Exception{ if(i == 0){ throw new Exception("abc"); } return i-1; } long func2(long i){ if(i == 0){ return i + 1; } return i -1; } void test1(){ Date begin = new Date(); long total = 0; for(long i = 1; i < size; ++i){ try { total += func1(i); } catch (Exception e) { e.printStackTrace(); } } Date end = new Date(); System.out.println(total); System.out.println("test1 time:" + (end.getTime() - begin.getTime())); } void test2(){ Date begin = new Date(); long total = 0; for(long i = 1; i < size; ++i){ total += func2(i); } Date end = new Date(); System.out.println(total); System.out.println("test2 time:" + (end.getTime() - begin.getTime())); } }

总结:异常是个很有用的功能,在不抛出异常时,开销可以忽略不计。

在C++中也是如此。

"Java中的异常对程序效率有没有影响"的内容就介绍到这里了,感谢大家的阅读。如果想了解更多行业相关的知识可以关注网站,小编将为大家输出更多高质量的实用文章!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report