Search code examples
javaperformanceoptimizationjvmatomic

Is there any performance difference between a value comparison and a value assignment?


Consider the following two code examples:

Example 1.

public void setValue(int value)
{
    mValue = value;
}

Example 2.

public void setValue(int value)
{
    if (mValue != value)
    {
        mValue = value;
    }
}

Pretend you've been tasked to optimise some Java code to the absolute max, beyond all common sense.

Would the second code example be an optimisation of the first? By that I mean, is there any difference (no matter how miniscule) between an if condition check and an int assignment at the lowest levels of Java or the JVM?


Solution

  • The second is likely to be an anti-optimization since on modern processors branching tends to be expensive (primarily because branch misprediction is extremely costly).

    The only way to find out for sure is to profile your code on representative inputs. See How do I write a correct micro-benchmark in Java? for some pointers on how to set up a meaningful micro-benchmark.

    Bear in mind that if the code in question doesn't account for a significant fraction of the overall CPU time, all optimizations in the world won't make a lot of difference to the overall performance of your applications.