Java 方法调用与使用变量 [英] Java Method invocation vs using a variable

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

问题描述

最近,我与我的团队负责人讨论了使用临时变量与调用 getter 方法的问题.长期以来,我一直认为,如果我知道我将不得不多次调用一个简单的 getter 方法,我会将它放入一个临时变量中,然后改用该变量.我认为这在风格和性能方面都会更好.然而,我的领导指出,在 Java 4 和更新的版本中,这在某种程度上是不正确的.他相信使用更小的变量空间,所以他告诉我,与使用临时变量相比,调用 getter 方法对性能的影响可以忽略不计,因此使用 getter 更好.然而,我并不完全相信他的论点.大家怎么看?

Recently I got into a discussion with my Team lead about using temp variables vs calling getter methods. I was of the opinion for a long time that, if I know that I was going to have to call a simple getter method quite a number of times, I would put it into a temp variable and then use that variable instead. I thought that this would be a better both in terms of style and performance. However, my lead pointed out that in Java 4 and newer editions, this was not true somewhat. He is a believer of using a smaller variable space, so he told me that calling getter methods had a very negligible performance hit as opposed to using a temp variable, and hence using getters was better. However, I am not totally convinced by his argument. What do you guys think?

推荐答案

永远不要为了性能而编码,永远为了可读性而编码.让编译器完成工作.

Never code for performance, always code for readability. Let the compiler do the work.

他们可以改进编译器/运行时以更快地运行好的代码,突然之间,您的快速"代码实际上降低了系统速度.

They can improve the compiler/runtime to run good code faster and suddenly your "Fast" code is actually slowing the system down.

Java 编译器 &运行时优化似乎首先解决更常见/可读的代码,因此与刚刚干净编写的代码相比,您的优化"代码更有可能在以后被取消优化.

Java compiler & runtime optimizations seem to address more common/readable code first, so your "Optimized" code is more likely to be de-optimized at a later time than code that was just written cleanly.

注意:

这个答案指的是 Java 代码技巧",就像所引用的问题一样,不错的编程可能会将循环级别从 O(N) 提高到 O(N^2).通常编写干净、DRY 的代码并在修复它之前等待操作明显花费太长时间.除非您是游戏设计师,否则您几乎永远不会达到这一点.

This answer is referring to Java code "Tricks" like the question referenced, not bad programming that might raise the level of loops from an O(N) to an O(N^2). Generally write clean, DRY code and wait for an operation to take noticeably too long before fixing it. You will almost never reach this point unless you are a game designer.

这篇关于Java 方法调用与使用变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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