在Java中,通过getter引用字段和通过变量引用字段之间存在性能差异吗? [英] In Java is there a performance difference between referencing a field through getter versus through a variable?

查看:95
本文介绍了在Java中,通过getter引用字段和通过变量引用字段之间存在性能差异吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这样做之间有什么区别

Field field = something.getSomethingElse().getField();
if (field == 0) {
//do something    
}
somelist.add(field);

if (something.getSomethingElse().getField() == 0) {
//do something    
}
somelist.add(something.getSomethingElse().getField());

通过getter对该字段的引用会导致性能下降,还是与引用已分配的变量相同?我了解该变量只是对内存空间的引用,因此getter应该只是获得该内存空间的另一种方法.

Do references to the field through getters incur a performance penalty or is it the same as referencing an assigned variable? I understand that the variable is just a reference to the memory space, so the getter should just be another way to get at that memory space.

请注意,这是一个学术问题(只是好奇的学校),而不是一个实际问题.

Note that this is an academic question (school of just curious) rather then a practical one.

推荐答案

假定getSomethingElse()被定义为

public SomethingElse getSomethingElse() {
    return this.somethingElse;
}

性能差异将很小(如果内联,则为零).但是,在现实生活中,您不能总是确定情况是否如此-幕后可能会发生一些处理(不一定在对象本身中,而是通过AOP代理进行).因此,将结果保存在变量中以进行重复访问可能是个好主意.

performance difference will be minimal (or zero if it'll get inlined). However, in real life you can not always be sure that's the case - there may be some processing happening behind the scenes (not necessarily in the object itself but, say, via AOP proxy). So saving the result in the variable for repeat access may be a good idea.

这篇关于在Java中,通过getter引用字段和通过变量引用字段之间存在性能差异吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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