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

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

问题描述

最近我和我的团队负责人讨论了使用临时变量与调用getter方法的问题。很长一段时间我认为,如果我知道我将不得不多次调用一个简单的getter方法,我会将它放入一个临时变量然后使用该变量。我认为这在风格和性能方面都会更好。但是,我的主管指出,在Java 4和更新版本中,这有点不正确。他相信使用一个较小的变量空间,所以他告诉我,调用getter方法的性能影响非常小,而不是使用temp变量,因此使用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.

tl; dr:

这个答案指的是Java代码Tricks,就像引用的问题一样。它不是指正确的设计。例如,我编写了一个发现例程来联系B类网络中的每台计算机(64k地址) - 线程不是一个选项,它不是优化,而是软件设计。对ArrayList进行插入排序只是糟糕的编程,将其切换到LinkedList不是优化,这是一个错误修复!

This answer is referring to Java code "Tricks" like the question referenced. It is not referring to correct design. For instance, I wrote a discovery routine to contact every computer in a class B network (64k addresses)--threading that was not an option and it was not an optimization, it was software design. Doing an insertion sort into an ArrayList is just bad programming, switching it to a LinkedList is not an optimization, it's a bug fix!

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

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