在下面的代码中,我们进行了listType.getDescription()两次调用:
for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
if (listType.getDescription() != null)
{
children.add(new SelectItem( listType.getId() , listType.getDescription()));
}
}
Run Code Online (Sandbox Code Playgroud)
我倾向于重构代码以使用单个变量:
for (ListType listType: this.listTypeManager.getSelectableListTypes())
{
String description = listType.getDescription();
if (description != null)
{
children.add(new SelectItem(listType.getId() ,description));
}
}
Run Code Online (Sandbox Code Playgroud)
我的理解是JVM以某种方式针对原始代码进行了优化,尤其是嵌套调用children.add(new SelectItem(listType.getId(), listType.getDescription()));.
比较两个选项,哪一个是首选方法,为什么?这就是内存占用,性能,可读性/易用性以及其他我现在不想到的内容.
后一个代码片段何时变得比前者更有利,也就是说,listType.getDescription()当使用临时局部变量变得更加理想时,是否存在任何(近似)调用次数,因为listType.getDescription()总是需要一些堆栈操作来存储this对象?
我更喜欢使用局部变量而不是多次调用同一个方法.
/*
* I prefer this
*/
Vehicle vehicle = person.getVehicle()
if (vehicle instanceof Car) {
Car car = (Car) vehicle;
car.openSunroof();
} else if (vehicle instanceof Bike) {
Bike bike = (Bike) vehicle;
bike.foldKickstand();
}
/*
* Rather than this
*/
if (person.getVehicle() instanceof Car) {
Car car = (Car) person.getVehicle();
car.openSunroof();
} else if (person.getVehicle() instanceof Bike) {
Bike bike = (Bike) person.getVehicle();
bike.foldKickstand();
}
Run Code Online (Sandbox Code Playgroud)
你更喜欢哪个?为什么?
我有以下场景..我多次遇到类似的场景。以下两个选项中哪个更可取?
选项1:
String result = ( getDetails(...) == null ) ? "" : getDetails(...);
Run Code Online (Sandbox Code Playgroud)
选项 2:
String returnValue = getDetails(...);
String result = ( returnValue == null ) ? "" : returnValue;
Run Code Online (Sandbox Code Playgroud)
哪个更可取和/或更好的做法。?
我知道这很简单,但我找不到任何问题。
当我检查列表是否为空然后迭代它时,它对性能有何影响?
我有以下代码,我想知道第二次调用 getContainers() 是否再次执行该方法,或者编译器正在保存列表,因此不必再次运行 getContainers() 。
if (getContainers() != null)
{
for (Container container : getContainers())
{...
Run Code Online (Sandbox Code Playgroud)
如果这不是真的,我正在考虑做类似下面代码的事情,但这似乎很天真。
List<Container> listC = getContainers();
if (listC != null)
{
for (Container container : listC)
{...
Run Code Online (Sandbox Code Playgroud)