Java优化:局部变量或函数调用 [英] Java optimization : local variable or function call

查看:297
本文介绍了Java优化:局部变量或函数调用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

你会做什么?

  doThings(folder.getInstructions()); 
for(Instruction instruction:folder.getInstructions()){
// do things
}
functionCall(folder.getInstructions());

或者这个:

  instructions = folder.getInstructions(); 
doThings(指令)
for(指令指令:指令){
//做事情
}
functionCall(指令);

最重要的是,我想知道何时将值存储在局部变量中更有效率,以及何时更好地进行函数调用。

解决方案

更具可读性更高效。临时表达式和局部变量需要相同的空间,从CPU / JVM的角度来看,它没有多大区别。 JVM将更好地优化/使用它。



但是如果 getInstructions()方法调用很昂贵,缓存它在局部变量中。如果它只是一个简单的吸气剂,它无论如何都会被内联。另外恕我直言,在您的特定情况下,局部变量 更具可读性,如果 getInstructions()可能会有不同的结果,可能更正确。


Which would you do ?

 doThings(folder.getInstructions()) ;
 for (Instruction instruction : folder.getInstructions()) {
    // do things
 }
functionCall(folder.getInstructions()) ;

Or this :

instructions = folder.getInstructions() ;
doThings(instructions)
for (Instruction instruction : instructions) {
  // do things
}
functionCall(instructions) ;

Above all, I would like to know when it is more efficient to store a value in a local variable, and when it is better to make function calls.

解决方案

More readable is more efficient. Temporary expressions and local variables need the same space and from CPU/JVM perspective it doesn't make much difference. JVM will do a better job optimizing/inling it.

However if getInstructions() method call is expensive, cache it in local variable. If it's just a plain getter, it will be inlined anyway. Also IMHO in your particular case local variable is more readable and maybe even more correct if getInstructions() may have different results over time.

这篇关于Java优化:局部变量或函数调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆