Java:在if中初始化条件(性能)

时间:2014-12-08 10:21:18

标签: java performance if-statement conditional-statements

我正在寻找在if条件中启动变量的可能性,因此它仅在条件范围内有效。

示例:我想转换它:

String tmp;
if ((tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is valid in this scope
    // do something with tmp
}
// tmp is valid here too

进入类似的东西:

if ((String tmp = functionWithALotOfProcessingTime()) != null)
{
    // tmp is *ONLY* in this scope valid
    // do something with tmp
}

3 个答案:

答案 0 :(得分:3)

我可以想到两种方法:

  • 您需要额外的范围{...}try{...}catch...,并在该范围内声明tmp

  • 将您的if逻辑包装在私有方法中,并在方法中声明tmp,以便在您的主逻辑中,您无法访问tmp

答案 1 :(得分:2)

尝试这样的事情:

{
    /*
     * Scope is restricted to the block with '{}' braces 
     */
    String tmp; 
    if ((tmp = functionWithALotOfProcessingTime()) != null) {
        // tmp is valid in this scope
        // do something with tmp
    }
}

tmp = "out of scope"; // Compiler Error - Out of scope (Undefined)

答案 2 :(得分:1)

我建议利用Optional API:

Optional.ofNullable(functionWithALotOfProcessingTime()).ifPresent(tmp -> {
   // do something with tmp
});

注意:Java 8中引入了Optional。