tags:

views:

170

answers:

3

Hey Guys,

Just a quick question what would be more expensive in Java?

   double test = 5;
   double test1 = 5;

or

   double test = 5;
   double test1 = test;
+18  A: 

Neither. Java has a very good optimiser that will cause the exact same code to be generated in this example.

The compiler looks at the assignment double test1 = test; and can work out that at this point test is a constant equal to 5 and completely optimise the assignment away.

This is also why you shouldn't be afraid to expand out numeric values, ie.

int timeout = 60 * 60 * 2   // 2 hours in seconds

That entirely aside, this is very much a case of micro-optimisation that will never return anything worth noting. Worry about that network connection that's holding up the works for several seconds instead.

Matthew Scharley
That's not even micro-optimization. We need to coin a new term for crap like this. Nano-optimization perhaps?
Michael Borgwardt
Actually `javac` does not optimize this to the exact same code; I tested this with Oracle Java 1.6.0 update 20 (decompile with `javap -c`). The JIT probably will optimize this. But ofcourse I agree that micro-optimisation like this is (almost) never worth spending time on.
Jesper
@Jesper that's interesting, because this is one of the most basic optimisations there is, and I always hear about how well java optimises things.
Matthew Scharley
In Sun's Java implementation, `javac` does very little optimisations - most of it is left to the JIT.
Jesper
+3  A: 

The difference between the two should be negligible. I imagine the constant would be a tiny bit faster, since there's no loading of test's value, but really...it's not worth your time to worry about it. Readability is far more important than the cycle or two you might conceivably save.

cHao
A: 

My first impulse is to say, write a small looping program and test it. However it might be more complicated than that.

Java can do all sorts of optimisation stuff after you have written the code, and this is the sort of stuff that they focus on. So that makes it harder to answer, and it probably depends on the specific JRE and code.

While I understand that this is an interesting academic question, in practical terms the answer probably is 'does not matter much' Other parts of your code will usually be making more of a bottle neck.

For your specific example, I have a feeling that '5' may be a special case, where there is a system pool of static integers, I know they do that with strings. Does anyone know?

Jon
Some JRE's will even optimise away entire loop constructs if it doesn't do anything thing productive.
Matthew Scharley