is checking a boolean faster than setting a boolean in java?

前端 未结 5 1290
死守一世寂寞
死守一世寂寞 2021-02-19 03:16

This:

if (var) {
    var = false;
}

Versus this:

var = false;

Is there a speed difference?

5条回答
  •  情书的邮戳
    2021-02-19 03:31

    Here's another cheap "benchmark" (which almost doesn't deserve the term). To me, the results of Monkey Wrench's benchmark were not clearly speaking in regards to OP's question, so I thought I should put it here, too.

    Result (under these conditions, and quite few tests only): Checking a local boolean before writing it is better than writing it often if not necessary.

    public static void main(String[] args) {
    
        final Random r = new Random(0);
    
        boolean b = false;
        boolean decision;
    
        long startTime;
        long endTime;
    
        startTime = System.currentTimeMillis();
        for (long i = 0; i < 1000000000; i++) {
            decision = r.nextDouble() > 0.1; // Will be true MOST of the time.
    
            if (decision) {
    
                // if (!b) {
                    b = true;
                // }
    
            }
        }
        endTime = System.currentTimeMillis();
    
        System.err.println(endTime - startTime);
        System.err.println(b);
    
        System.exit(0);
    }
    
    With bluntly writing (ms):
    18139
    18140
    18196
    (18220)
    (18181)
    ----------
    Average of 3: 18158.333333333333333333333333333
    Average of 5: 18175.2
    
    
    With checking before writing (ms):
    18097
    18109
    18115
    (18129)
    (18133)
    ----------
    Average of 3: 18107
    Average of 5: 18116.6
    
    
    With checking, it only takes this % (3 samples): 99.71730151445617255621844882974
    With checking, it only takes this % (5 samples): 99.677582640080989480170782164708
    

    With checking, it takes about 99.7 % of the blunt-writing time. If the write would otherwise happen unnecessarily very often. In this crappy "benchmark", that is.

提交回复
热议问题