Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

This:

if (var) {
    var = false;
}

Versus this:

var = false;

Is there a speed difference?

like image 355
a113nw Avatar asked Apr 22 '14 19:04

a113nw


1 Answers

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.

like image 65
Nitsan Wakart Avatar answered Sep 20 '22 14:09

Nitsan Wakart