Search code examples
variablesoptimization

Is it faster to 'check for inequality and set' or just 'directly set' variables


Which one is faster:

if (someValue != otherValue) someValue = otherValue;

or

someValue = otherValue;

Or will they be optimized into the same code?


Solution

  • This is a case of micro-optimization (see Jeff Atwood's 2005 post on the subject). If you're actually worrying about which to use in a project, don't. There's a very high chance that it just doesn't matter at all.

    However, if you're instead interested in understanding why there might be a difference underneath the hood, keep reading.

    Whether or not there's a speed difference (and even which one might be better in terms of overall performance) depends on factors including the data type of the variable(s), the programming language, and the users' system architectures.

    In C++ using ints, your "directly set" snippet will be faster than your "check and set" snippet in the vast majority of cases. This is because the compare and branch (or compare and conditional move, or equivalent) that are executed when the values are equal will actually be slower than the (unneeded) move that would have been executed. However, the difference is so small that you'd have to do this many times before it made a difference. Furthermore, an optimizing compiler will probably remove the dead code for you.

    There are possible exceptions, of course. One potential case is a cache-coherent multiprocessor system where writes cause other processors to invalidate their cache lines even when the value doesn't change (I'm not sure how often this is the case, but it seems at least possible). Then, it may be better to do the check first if the variable is read often but changed infrequently (that is, the code runs many times, but it's usually the case that someValue == otherValue). Similarly, in a memory-bound program, it might make sense to do the check if your cache always flushes to memory (for a write-through cache) or sets the dirty bit (for a write-back cache) on a write even if the value hasn't changed (again, sounds plausible).

    If someValue and otherValue are more complex types where comparison and/or assignment have been overridden, the two given pieces of code may not even be equivalent, to say nothing of the performance.