简体   繁体   English

在Java中过度使用get()是否效率低下?

[英]Is using get() excessively in Java inefficient?

I was wondering whether it was more efficient to use get() excessively on an object or store the return of the get() in a variable and use that. 我想知道在对象上过度使用get()或在变量中存储get()的返回是否更有效并使用它。 For example, would it be more efficient to do this: 例如,执行此操作会更有效:

someObject.setColor(otherObject.getColor().r, otherObject.getColor().g, 
         otherObject.getColor().b);

or to store the it in a variable like this 或者将它存储在这样的变量中

Color color = otherObject.getColor();
someObject.setColor(color.r, color.g, color.b);

Option 1: you write the code as in example 1. 选项1:您按照示例1编写代码。

  • the java runtime might or might not optimize the code (to turn it into something like your example 2) java运行时可能会也可能不会优化代码(将其转换为类似于示例2的代码)
  • harder to read 更难读

Option 2: you write the code as in example 2. 选项2:您编写示例2中的代码。

  • does not rely on optimizations by the java runtime 不依赖于java运行时的优化
  • easier to read 更容易阅读

In my experience the runtime difference can be ignored (you can't measure the difference if not executed within a giant loop), but writing clean and understandable code is what counts. 根据我的经验,可以忽略运行时差异(如果不在巨型循环中执行,则无法衡量差异),但编写干净且易于理解的代码非常重要。

In example#2 在示例#2中

Color color = otherObject.getColor();
someObject.setColor(color.r, color.g, color.b);

you are only creating a reference to the original object, so you are not using any considerable "extra" memory. 您只是创建对原始对象的引用,因此您没有使用任何可观的“额外”内存。 plus it is more readable so +1 for example#2 加上它更具可读性,所以+1例如#2

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

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