在for循环中前后递增 [英] Pre and post increment in a for loop

查看:235
本文介绍了在for循环中前后递增的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



示例代码:

$ b $在java中的for循环中, b

  for(int i = 0; i <10; i ++)



$ p
$ b $ pre $ for(int i = 0; i <10; ++ i)

我注意到当我做一个预先增量时,执行时间会减少, -增量。任何建议,为什么这可能是这样的?感谢。

解决方案

我编译了一个最小的例子(Oracle jdk1.7.0_07):

  public void post(){
for(int i = 0; i <10; i ++){

}


public void pre(){
for(int i = 0; i <10; ++ i){

}
}

两种方法产生相同的字节码:

  0 iconst_0 
1 istore_1
2 goto 8(+6)
5 iinc 1 by 1
8 iload_1
9 bipush 10
11 if_icmplt 5(-6)
14返回


Is it more performant to do a pre-increment vs a post-increment in a for loop in java ?

Sample code :

for (int i=0; i<10; i++)

and

for (int i=0; i<10; ++i)

I notice that when i do a pre-increment, the execution time is lesser that when i do the post-increment. Any suggestions on why this might be the case ? thanks.

解决方案

I compiled a minimal example (Oracle jdk1.7.0_07):

public void post() {
    for (int i=0; i<10; i++) {

    }
}

public void pre() {
    for (int i=0; i<10; ++i) {

    }
}

Both methods produced the same exact bytecode:

 0 iconst_0
 1 istore_1
 2 goto 8 (+6)
 5 iinc 1 by 1
 8 iload_1
 9 bipush 10
11 if_icmplt 5 (-6)
14 return

这篇关于在for循环中前后递增的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆