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

前端 未结 6 1278
不知归路
不知归路 2020-12-29 06:04

Consider the following 2 scenarios:

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

OR

boolean b = false;         


        
6条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-29 06:43

    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…

提交回复
热议问题