Just curious, which code is more effective:
if (myClass.getSomeValue() != myValue) myClass.setSomeValue(myValue);
or simply
myClass.setSomeValue(myValue);
, whe开发者_开发知识库re getSomeValue()
and setSomeValue(...)
are simple getter-setter pair? It's clear, then second will be faster in case of .equals()
usage, so we using just !=
.
There is no point in micro-optimizing, especially not in bytecode-based languages like Java. Thanks to Hotspot, the actual machine level instructions executed for the two code snippets may widely differ based on the actual environment, usage patterns etc.
Therefore, even if you have a real need to do this, I don't think there is a general answer to your question without knowing how often
myValue
is actually different from the original.
The first will be obviously faster.
Don't optimize before you know where the bottleneck is. Remember, premature optimization is the root of all evil. Usual bottlenecks are database, network, creating lots of objects. Simply checking a value is not a bottleneck.
BEWARE:
!=
andequals()
are not the same. Former checks for identity (does a reference point to the same object), the later checks for equality (if two distinct objects have the same value).
I would assume that the second because you are still doing a memory access while getting the variable reference even if you aren't setting it in the end. The bottleneck isn't probably the test but the memory access.
The second is faster just because the first is the same as the second with one additional method call
only this will be better
myClass.setSomeValue(myValue);
condition checking is heavy
1
if (myClass.getSomeValue() != myValue) myClass.setSomeValue(myValue);
there will be following operations :
Best Case
1.a method call myClass.getSomeValue()
2.comparission with myValue
Worst Case
1.a method call myClass.getSomeValue()
2.comparission with myValue
3.a method call myClass.setSomeValue(myValue)
2
while in myClass.setSomeValue(myValue);
Any Case
1.a method call myClass.setSomeValue(myValue)
精彩评论