Loop counter in Java API

后端 未结 3 1848
野趣味
野趣味 2020-12-01 22:36

All,

While going through some of the files in Java API, I noticed many instances where the looping counter is being decremented rather than increment. i.e. in

3条回答
  •  不知归路
    2020-12-01 23:10

    I've compiled two simple loops with eclipse 3.6 (java 6) and looked at the byte code whether we have some differences. Here's the code:

    for(int i = 2; i >= 0; i--){}
    for(int i = 0; i <= 2; i++){}
    

    And this is the bytecode:

    // 1st for loop - decrement 2 -> 0
     0 iconst_2
     1 istore_1      // i:=2
     2 goto 8
     5 inc 1 -1      // i+=(-1)
     8 iload_1
     9 ifge 5        // if (i >= 0) goto 5
    
    // 2nd for loop - increment 0 -> 2
    12 iconst_0 
    13 istore_1      // i:=0
    14 goto 20
    17 inc 1 1       // i+=1
    20 iload_1
    21 iconst 2
    22 if_icmple 17  // if (i <= 2) goto 17
    

    The increment/decrement operation should make no difference, it's either +1 or +(-1). The main difference in this typical(!) example is that in the first example we compare to 0 (ifge i), in the second we compare to a value (if_icmple i 2). And the comaprision is done in each iteration. So if there is any (slight) performance gain, I think it's because it's less costly to compare with 0 then to compare with other values. So I guess it's not incrementing/decrementing that makes the difference but the stop criteria.

    So if you're in need to do some micro-optimization on source code level, try to write your loops in a way that you compare with zero, otherwise keep it as readable as possible (and incrementing is much easier to understand):

     for (int i =  0; i <= 2; i++) {}  // readable
     for (int i = -2; i <= 0; i++) {}  // micro-optimized and "faster" (hopefully)
    

    Addition

    Yesterday I did a very basic test - just created a 2000x2000 array and populated the cells based on calculations with the cell indices, once counting from 0->1999 for both rows and cells, another time backwards from 1999->0. I wasn't surprised that both scenarios had a similiar performance (185..210 ms on my machine).

    So yes, there is a difference on byte code level (eclipse 3.6) but, hey, we're in 2010 now, it doesn't seem to make a significant difference nowadays. So again, and using Stephens words, "don't waste your time" with this kind of optimization. Keep the code readable and understandable.

提交回复
热议问题