简体   繁体   English

什么更贵? 转让还是声明?

[英]What is more expensive? Assignment or declaration?

Just a quick question what would be more expensive in Java? 只是一个简单的问题,在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. Java有一个非常好的优化器,它将在此示例中生成完全相同的代码。

The compiler looks at the assignment double test1 = test; 编译器查看赋值double test1 = test; and can work out that at this point test is a constant equal to 5 and completely optimise the assignment away. 并可以得出结论,此时test是一个等于5的常数,可以完全优化分配。

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. 编写代码后,Java可以完成各种优化工作,而这正是他们关注的工作。 So that makes it harder to answer, and it probably depends on the specific JRE and code. 因此,这使回答变得更加困难,并且可能取决于特定的JRE和代码。

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. 对于您的特定示例,我觉得“ 5”可能是一种特殊情况,其中有一个静态整数系统池,我知道它们使用字符串来实现。 Does anyone know? 有人知道吗?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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