Which of these pieces of code is faster in Java?

前端 未结 16 2028
囚心锁ツ
囚心锁ツ 2020-11-30 04:25

a) for(int i = 100000; i > 0; i--) {}

b) for(int i = 1; i < 100001; i++) {}

The answer is t

16条回答
  •  再見小時候
    2020-11-30 04:59

    I've been making tests for about 15 minutes now, with nothing running other than eclipse just in case, and I saw a real difference, you can try it out.

    When I tried timing how long java takes to do "nothing" and it took around 500 nanoseconds just to have an idea.

    Then I tested how long it takes to run a for statement where it increases:

    for(i=0;i<100;i++){}

    Then five minutes later I tried the "backwards" one:

    for(i=100;i>0;i--)

    And I've got a huge difference (in a tinny tiny level) of 16% between the first and the second for statements, the latter being 16% faster.

    Average time for running the "increasing" for statement during 2000 tests: 1838 n/s

    Average time for running the "decreasing" for statement during 2000 tests: 1555 n/s

    Code used for such tests:

    public static void main(String[] args) {
        long time = 0;  
        for(int j=0; j<100; j++){
        long startTime = System.nanoTime();
        int i;
            /*for(i=0;i<100;i++){
    
            }*/
            for(i=100;i>0;i--){
    
            }
        long endTime = System.nanoTime();
        time += ((endTime-startTime));
        }
        time = time/100;
        System.out.print("Time: "+time);
    }
    

    Conclusion: The difference is basically nothing, it already takes a significant amount of "nothing" to do "nothing" in relation to the for statement tests, making the difference between them negligible, just the time taken for importing a library such as java.util.Scanner takes way more to load than running a for statement, it will not improve your application's performance significantly, but it's still really cool to know.

提交回复
热议问题