【发布时间】:2013-10-18 09:07:56
【问题描述】:
在下面的代码中,我们调用listType.getDescription() 两次:
for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
if (listType.getDescription() != null)
{
children.add(new SelectItem( listType.getId() , listType.getDescription()));
}
}
我倾向于重构代码以使用单个变量:
for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
String description = listType.getDescription();
if (description != null)
{
children.add(new SelectItem(listType.getId() ,description));
}
}
我的理解是 JVM 以某种方式针对原始代码进行了优化,尤其是像 children.add(new SelectItem(listType.getId(), listType.getDescription())); 这样的嵌套调用。
比较这两个选项,哪一个是首选方法,为什么?那是在内存占用、性能、可读性/易用性以及我现在没有想到的其他方面。
后一种代码 sn-p 何时比前者更有利,也就是说,当使用临时局部变量变得更可取时,是否有任何(近似)数量的 listType.getDescription() 调用,因为 listType.getDescription() 总是需要一些存储this对象的堆栈操作?
【问题讨论】:
-
如果调用次数足够多,JIT 会尽可能对其进行记忆。其余的看我的回答。
标签: java performance readability memory-consumption