java快速添加try_java – 为什么添加一个try块使程序更快?

我正在使用以下代码来测试try块的速度.令我吃惊的是,try块使其更快.为什么?

public class Test {

int value;

public int getValue() {

return value;

}

public void reset() {

value = 0;

}

// Calculates without exception

public void method1(int i) {

value = ((value + i) / i) << 1;

// Will never be true

if ((i & 0xFFFFFFF) == 1000000000) {

System.out.println("You'll never see this!");

}

}

public static void main(String[] args) {

int i;

long l;

Test t = new Test();

l = System.currentTimeMillis();

t.reset();

for (i = 1; i < 100000000; i++) {

t.method1(i);

}

l = System.currentTimeMillis() - l;

System.out.println("method1 took " + l + " ms, result was "

+ t.getValue());

// using a try block

l = System.currentTimeMillis();

t.reset();

for (i = 1; i < 100000000; i++) {

try {

t.method1(i);

} catch (Exception e) {

}

}

l = System.currentTimeMillis() - l;

System.out.println("method1 with try block took " + l + " ms, result was "

+ t.getValue());

}

}

我的机器正在运行64位Windows 7和64位JDK7.我得到以下结果:

method1 took 914 ms, result was 2

method1 with try block took 789 ms, result was 2

我已经运行了很多次代码,每次我得到几乎相同的结果.

更新:

这是在MacBook Pro,Java 6上运行测试十次的结果.Try-catch使该方法更快,与Windows相同.

method1 took 895 ms, result was 2

method1 with try block took 783 ms, result was 2

--------------------------------------------------

method1 took 943 ms, result was 2

method1 with try block took 803 ms, result was 2

--------------------------------------------------

method1 took 867 ms, result was 2

method1 with try block took 745 ms, result was 2

--------------------------------------------------

method1 took 856 ms, result was 2

method1 with try block took 744 ms, result was 2

--------------------------------------------------

method1 took 862 ms, result was 2

method1 with try block took 744 ms, result was 2

--------------------------------------------------

method1 took 859 ms, result was 2

method1 with try block took 765 ms, result was 2

--------------------------------------------------

method1 took 937 ms, result was 2

method1 with try block took 767 ms, result was 2

--------------------------------------------------

method1 took 861 ms, result was 2

method1 with try block took 744 ms, result was 2

--------------------------------------------------

method1 took 858 ms, result was 2

method1 with try block took 744 ms, result was 2

--------------------------------------------------

method1 took 858 ms, result was 2

method1 with try block took 749 ms, result was 2

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值