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语句没有关系。

浙公网安备 33010602011771号