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

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

This:

if (var) {
    var = false;
}

Versus this:

var = false;

Is there a speed difference?

5条回答
  •  执念已碎
    2021-02-19 03:40

    Several things come into play, ultimate effect on actual performance is something you will need to measure for your use case. I assume this is a method you have found to happen A LOT:

    1. Branch prediction - if var is almost always false, which is what the code suggests, the branch predictor will be almost always right. If the field changes often then this is will become an often mispredicted branch and will be expensive.

    2. Read miss - If var is mostly read (and read A LOT) then avoiding changing without cause can help your software by not invalidating the cache line it sits on. If you write to it every other core who reads it (and anything on the same cache line) will need to get a fresh copy experiencing a read miss. This means the above method may be worth making slower for the sake of making reads have more consistent speed.

    3. Write cost vs. read cost - if var is volatile then it's write is a LoadStore barrier which is quite expensive. Reading a volatile (a LoadLoad barrier) is rather cheap by comparison (a cache hit for an often used and hardly changed value). This can make the branch very cheap by comparison.

    This is an optimization people make, and examples can be found in the JDK (IIRC), I assume you have a reason to consider it.

提交回复
热议问题