For-loop with and without an empty body takes same amount of time

Viewed 169

I've noticed that both of the following loops take the same amount of time: ~ 1.2 seconds.

double count = Math.pow(10, 9);
for (int i = 0; i < count; i++) {
    int y = 10;
    int x = 3*y;
    x = 100*y;
    int[] arr = new int[3];
    arr[0] = 1;
}
double count = Math.pow(10, 9);
for (int i = 0; i < count; i++) {
    //nothing
}

Why would they finish in the same time? These for-loops only increment and do 1 comparison, so 2 actions per iteration. I would think the first one would take about 3 times longer to finish, since it does 7 actions whereas the second one does 2.

3 Answers

The answer is not because of optimization (or solely thereof - the byte code is generated). It is because the loop is a floating point loop and floating point operations are notoriously expensive. So the internal code is relatively faster or insignificant to the overall running time (as was alluded to by @j11john).

If you change the loop so it is int based, the two forms will run at significantly different speeds.

        long start = System.nanoTime();
        int count = (int)Math.pow(10, 9);
        int x = 0;
        for(int i = 0;i<count;i++) {
            int y = 10;
             x = 3*y;
            x = 100*y*x;
            int[] arr = new int[3];
            arr[0] = 1;
        
        }
        System.out.println((System.nanoTime()-start)/1_000_000_000.);
    }

8.4248E-5 vs 0.047076639 The latter time with the extra code.

So the similarity in both running times (as observed by the OP) is related to the nature of the loop (int vs double) and has very little to do with the code within the loop.

Surely the inside code of the loop isn't cpu expensive so is probably going to have the same time.

Related