简体   繁体   中英

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;

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.

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM