【问题标题】:Java: Initialize condition in If construct (performance)Java:在 If 构造中初始化条件(性能)
【发布时间】:2015-02-05 23:28:57
【问题描述】:

我正在寻找在 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
}

【问题讨论】:

  • Java 的作用域规则不是这样定义的。
  • 编译器会自动将变量的作用域限制在它被使用的地方。顺便说一句,这对性能没有影响,只是将变量的使用限制在预期使用的地方。
  • 本题不涉及性能问题。

标签: java performance if-statement conditional-statements


【解决方案1】:

我可以想到两种方法:

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

  • 将你的if逻辑包装在一个私有方法中,并在方法中声明tmp,这样在你的主逻辑中,你就不能访问tmp

【讨论】:

    【解决方案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)
    

    【讨论】:

    • 我不想要额外的范围,它会破坏代码的可读性
    • 在这种情况下,它不适用于 if 块。范围只是一种选择。
    • @Eun 您显然想要一个额外的范围,而在 Java 中您可以使用大括号来实现。
    • 接受,因为这是最接近的答案,顺便说一句,我知道我想要什么,我不想要什么。
    【解决方案3】:

    我建议利用可选 API:

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

    注意:可选是在 Java 8 中引入的。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 2018-08-02
      • 2020-02-13
      • 2015-09-11
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多