我在处理对象时遇到了困惑。我搜索了谷歌,但找不到要搜索的实际词。问题是:
我正在处理由其他对象组成的对象。例如:
public void mapObjects(A a, B b) {
a.setWeight(BigDecimal.valueOf(b.getWeight));
//Now my doubt lies here
if (a.getCharges.getDiscounts.getDiscountList != null) {
for(int i = 0; i < a.getCharges.getDiscounts.getDiscountList.size(); i++){
b.getList().get(0).setDiscountValue(a.getCharges.getDiscounts.getDiscountList.get(i).getValue());
b.getList().get(0).setDiscountName(a.getCharges.getDiscounts.getDiscountList.get(i).getValue);
}
}
}
上面的代码只是一个例子。我工作的项目使用类似类型的编码风格。 a.getCharges.getDiscounts.getDiscountList()
这类代码的使用总是让我很烦。因为我一次又一次地调用同一个语句。
当我问学长为什么我们不把这条语句保存到一个简单的List<>变量中。他告诉我它将使用额外的引用,这会增加开销。与一次又一次调用 getter 相比,使用变量的开销会大吗?
最佳答案
由于 Java 交换引用而不是实际对象,如果您使用局部变量,它只会在堆栈帧中添加一个引用变量条目。
- 这个内存会非常少,几乎可以忽略不计
- 此内存将在方法完成后释放,因为这将是方法的本地内存
尽管如此,如果您使用局部变量,您可以获得显着的性能提升。您在循环中多次提取相同的信息。
a.getCharges.getDiscounts.getDiscountList.size()
被多次调用。它应该是一个局部变量。b.getList().get(0)
被多次调用。它应该是一个局部变量。a.getCharges.getDiscounts.getDiscountList
被多次调用。它应该是一个局部变量。
将这些更改为局部变量会带来良好的性能提升,因为会节省不必要的方法调用。
关于java - 使用变量而不是长语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39909169/