Pre and post increment in a for loop [duplicate]

我的梦境 提交于 2019-12-12 05:27:38

问题


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.


回答1:


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



回答2:


Unless your loop body does next to nothing, this question is moot: the overhead of variable increment is zero. Even if the overhead stands out, its magnitude is completely unpredictable and can vary wildly even across different instantiations of the exact same JVM on the exact same hardware. The "wild" variation is, of course, within the range of 0..2 ns.




回答3:


Post-increment and pre-increment (or decrement) basically means if you are using pre-increment such as ++i this is evaluated before the rest of that code line is. If using post-increment such as i++ this is evaluated after the rest of the code line is. That is maybe why you're getting a "faster execution time".




回答4:


There is no such performance issue based on that. Both are exact same when it comes to performance. And there is no way you can claim ++i should use instead of i++, it is up to the logic we are going to handle. ++i means increment first then go to work while i++ means go to work and then increment. Have a look at the following questions.

How do the post increment (i++) and pre increment (++i) operators work in Java?

Language Independent example: Difference between i++ and ++i in a loop?



来源:https://stackoverflow.com/questions/15115530/pre-and-post-increment-in-a-for-loop

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!