2

Just curious, which code is more effective:

if (myClass.getSomeValue() != myValue) myClass.setSomeValue(myValue); 

or simply

myClass.setSomeValue(myValue); 

, where 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 !=.

1
  • The question isn't very clear. If you have two positive variables x and y, which is more? x + y, or just y? Commented Jan 4, 2011 at 9:33

5 Answers 5

7
  1. 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.

  2. 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.

Sign up to request clarification or add additional context in comments.

2 Comments

I know, that there is no point in it, but i am still curious :) So, you saying, check will be faster if they are often unequal?
@Frozen, I am not a JVM expert, but I would assume the opposite: if they are often unequal, the first version will often be check and set, which will be slower than a simple set. However, if the values are (almost) always equal, the first version will usually be a plain check, which I assume to be at least as fast (if not faster) than set.
5
  1. The first will be obviously faster.

  2. 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.

  3. BEWARE: != and equals() 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).

Comments

2

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.

Comments

1

The second is faster just because the first is the same as the second with one additional method call

Comments

1

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)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.