Which costs more while looping; assignment or an if-statement?

Viewed 12183

Consider the following 2 scenarios:

boolean b = false;
int i = 0;
while(i++ < 5) {
    b = true;
}

OR

boolean b = false;
int i = 0;
while(i++ < 5) {
    if(!b) {
        b = true;
    }
}

Which is more "costly" to do? If the answer depends on used language/compiler, please provide. My main programming language is Java.

Please do not ask questions like why would I want to do either.. They're just barebone examples that point out the relevant: should a variable be set the same value in a loop over and over again or should it be tested on every loop that it holds a value needed to change?

6 Answers

Actually, this is the question I was interested in… (I hoped that I’ll find the answer somewhere to avoid own testing. Well, I didn’t…)

To be sure that your (mine) test is valid, you (I) have to do enough iterations to get enough data. Each iteration must be “long” enough (I mean the time scale) to show the true difference. I’ve found out that even one billion iterations are not enough to fit to time interval that would be long enough… So I wrote this test:

for (int k = 0; k < 1000; ++k)
{
    {
        long stopwatch = System.nanoTime();

        boolean b = false;
        int i = 0, j = 0;
        while (i++ < 1000000)
            while (j++ < 1000000)
            {
                int a = i * j; // to slow down a bit
                b = true;
                a /= 2; // to slow down a bit more
            }

        long time = System.nanoTime() - stopwatch;
        System.out.println("\\tasgn\t" + time);
    }
    {
        long stopwatch = System.nanoTime();

        boolean b = false;
        int i = 0, j = 0;
        while (i++ < 1000000)
            while (j++ < 1000000)
            {
                int a = i * j; // the same thing as above
                if (!b)
                {
                    b = true;
                }
                a /= 2;
            }

        long time = System.nanoTime() - stopwatch;
        System.out.println("\\tif\t" + time);
    }
}

I ran the test three times storing the data in Excel, then I swapped the first (‘asgn’) and second (‘if’) case and ran it three times again… And the result? Four times “won” the ‘if’ case and two times the ‘asgn’ appeared to be the better case. This shows how sensitive the execution might be. But in general, I hope that this has also proven that the ‘if’ case is better choice.

Thanks, anyway…

Related