Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing logically similar "for loops"

Tags:

java

I came across simple java program with two for loops. The question was whether these for loops will take same time to execute or first will execute faster than second .

Below is programs :

public static void main(String[] args) {

        Long t1 = System.currentTimeMillis();
        for (int i = 999; i > 0; i--) {
            System.out.println(i);
        }
        t1 = System.currentTimeMillis() - t1;
        Long t2 = System.currentTimeMillis();
        for (int j = 0; j < 999; j++) {
            System.out.println(j);
        }
        t2 = System.currentTimeMillis() - t2;

        System.out.println("for loop1 time : " + t1);
        System.out.println("for loop2 time : " + t2);
    }

After executing this I found that first for loop takes more time than second. But after swapping there location the result was same that is which ever for loop written first always takes more time than the other. I was quite surprised with result. Please anybody tell me how above program works.

like image 835
mahesh Avatar asked Nov 17 '11 14:11

mahesh


2 Answers

The time taken by either loop will be dominated by I/O (i.e. printing to screen), which is highly variable. I don't think you can learn much from your example.

like image 104
Oliver Charlesworth Avatar answered Sep 18 '22 15:09

Oliver Charlesworth


The first loop will allocate 1000 Strings in memory while the second loop, regardsless of working forwards or not, can use the already pre-allocated objects.

Although working with System.out.println, any allocation should be neglible in comparison.

like image 33
Johan Sjöberg Avatar answered Sep 18 '22 15:09

Johan Sjöberg