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

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

This:

if (var) {
    var = false;
}

Versus this:

var = false;

Is there a speed difference?

5条回答
  •  忘掉有多难
    2021-02-19 03:41

    The "speed difference," if any, will depend entirely on the JVM. Any decent compiler should be able to optimize away the test, at which point the two are identical.

    Exception: If var is declared volatile the conditional version will always be slower.

    In any case, if performance is critical, the best option is to measure it under expected conditions (machine, system, JVM, typical load, etc.).

提交回复
热议问题