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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With