Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 672
XåpplI'-I0llwlg'I - Avatar asked Dec 12 '22 19:12

XåpplI'-I0llwlg'I -


2 Answers

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.

like image 199
NPE Avatar answered May 08 '23 16:05

NPE


NPE has good advice. One comment I'll add is that probably also depends on whether mValue is volatile, and what hardware you're running it on. For volatiles, a write can be several times more expensive than a read. One some hardware (I believe many mobile devices, for instance) a volatile read is pretty far from cheap, so that difference probably goes down.

like image 28
yshavit Avatar answered May 08 '23 16:05

yshavit