Skizit
Skizit

Reputation: 44862

What is more expensive? Assignment or declaration?

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

   double test = 5;
   double test1 = 5;

or

   double test = 5;
   double test1 = test;

Upvotes: 0

Views: 287

Answers (3)

Matthew Scharley
Matthew Scharley

Reputation: 132494

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.

Upvotes: 19

Jon
Jon

Reputation: 1047

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?

Upvotes: 0

cHao
cHao

Reputation: 86575

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.

Upvotes: 3

Related Questions