相关疑难解决方法(0)

在对象上调用getter而不是将其存储为局部变量(内存占用,性能)

在下面的代码中,我们进行了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对象?

java performance readability memory-consumption

30
推荐指数
2
解决办法
7215
查看次数

Java编码风格,局部变量vs重复方法调用

我更喜欢使用局部变量而不是多次调用同一个方法.

/*
 * 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)
  • 我相信第一种方式是更快一点
  • 我认为第二种方式违反了DRY原则
  • 我发现第一种方式更易读,更容易调试(......可以忽略不计,因为我可以跳过)
  • 我不想要处理改变对象状态的可能性

你更喜欢哪个?为什么?

java coding-style

11
推荐指数
2
解决办法
2247
查看次数

在调用函数两次和将返回值存储在变量中之间选择哪一个?

我有以下场景..我多次遇到类似的场景。以下两个选项中哪个更可取?

选项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)

哪个更可取和/或更好的做法。?

java optimization

5
推荐指数
1
解决办法
1695
查看次数

在java上检查列表是否为空会影响性能吗?

我知道这很简单,但我找不到任何问题。

当我检查列表是否为空然后迭代它时,它对性能有何影响?

我有以下代码,我想知道第二次调用 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)

java performance null list

0
推荐指数
1
解决办法
461
查看次数