Java try-catch性能分析

Java笔记

  在开发的过程中,我总是会有意无意的使用到try-catch语句,于是担心起它的使用会不会影响程序的性能?

结论:

在程序未抛出异常的时候,使用try-catch语句对程序性能【没有丝毫影响】。

验证代码:

public class Test {
public static void main(String[] args) {
test1();
test2();
}
// 不使用 try 语句
private static void test1() {
long start = System.nanoTime();
int count = 0;
for (int i = 0; i < 100000; i++) {
count += i;
}
System.out.println("time 1 : " + (System.nanoTime() - start));
}
// 使用 try 语句
private static void test2() {
long start = System.nanoTime();
int count = 0;
try {
for (int i = 0; i < 100000; i++) {
count += i;
}
} catch (Exception ex) {}
System.out.println("time 2 : " + (System.nanoTime() - start));
}
}
// 第一次测试结果
time 1 : 1283209
time 2 : 1340834
// 第二次测试结果
time 1 : 1815417
time 2 : 1780459
// 第三次测试结果
time 1 : 1621625
time 2 : 1659375

从以上3次验证结果可以看出:当程序不发生异常时,程序的性能跟是否编写try-catch语句没有关系。

posted @   ThinkStu  阅读(12)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律
点击右上角即可分享
微信分享提示