Loop counter in Java API

后端 未结 3 1846
野趣味
野趣味 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:27

    When in doubt, benchmark.

    public class IncDecTest
    {
        public static void main(String[] av)
        {
            long up = 0;
            long down = 0;
            long upStart, upStop;
            long downStart, downStop;
            long upStart2, upStop2;
            long downStart2, downStop2;
    
            upStart = System.currentTimeMillis();
            for( long i = 0; i < 100000000; i++ )
            {
                up++;
            }
            upStop = System.currentTimeMillis();
    
            downStart = System.currentTimeMillis();
            for( long j = 100000000; j > 0; j-- )
            {
                down++;
            }
            downStop = System.currentTimeMillis();
    
            upStart2 = System.currentTimeMillis();
            for( long k = 0; k < 100000000; k++ )
            {
                up++;
            }
            upStop2 = System.currentTimeMillis();
    
            downStart2 = System.currentTimeMillis();
            for( long l = 100000000; l > 0; l-- )
            {
                down++;
            }
            downStop2 = System.currentTimeMillis();
    
            assert (up == down);
    
            System.out.println( "Up: " + (upStop - upStart));
            System.out.println( "Down: " + (downStop - downStart));     
            System.out.println( "Up2: " + (upStop2 - upStart2));
            System.out.println( "Down2: " + (downStop2 - downStart2));
        }
    }
    

    With the following JVM:

    java version "1.6.0_22"
    Java(TM) SE Runtime Environment (build 1.6.0_22-b04-307-10M3261)
    Java HotSpot(TM) 64-Bit Server VM (build 17.1-b03-307, mixed mode)
    

    Has the following output (ran it multiple times to make sure the JVM was loaded and to make sure the numbers settled down a little).

    $ java -ea IncDecTest
    Up: 86
    Down: 84
    Up2: 83
    Down2: 84
    

    These all come extremely close to one another and I have a feeling that any discrepancy is a fault of the JVM loading some code at some points and not others, or a background task happening, or simply falling over and getting rounded down on a millisecond boundary.

    While at one point (early days of Java) there might have been some performance voodoo to be had, it seems to me that that is no longer the case.

    Feel free to try running/modifying the code to see for yourself.

提交回复
热议问题