我有一个这样的循环:

for (int i = 0; i < max; i++) {
    String myString = ...;
    float myNum = Float.parseFloat(myString);
    myFloats[i] = myNum;
}

这是一个方法的主要内容,该方法的唯一目的是返回浮点数数组。我想让这个方法在出现错误时返回null,所以我把循环放在try…Catch block,像这样:

try {
    for (int i = 0; i < max; i++) {
        String myString = ...;
        float myNum = Float.parseFloat(myString);
        myFloats[i] = myNum;
    }
} catch (NumberFormatException ex) {
    return null;
}

但后来我也想到试一试……Catch块在循环中,像这样:

for (int i = 0; i < max; i++) {
    String myString = ...;
    try {
        float myNum = Float.parseFloat(myString);
    } catch (NumberFormatException ex) {
        return null;
    }
    myFloats[i] = myNum;
}

是否有任何理由,性能或其他方面,更喜欢其中一个?


编辑:共识似乎是,将循环放在try/catch中更干净,可能是在它自己的方法中。然而,关于哪个速度更快仍存在争议。有人能测试一下并给出一个统一的答案吗?


当前回答

你应该喜欢外面的版本而不是里面的版本。这只是规则的一个特定版本,将任何可以移动到循环外的东西移动到循环外。根据IL编译器和JIT编译器的不同,您的两个版本最终可能具有不同的性能特征,也可能没有。

另一方面,你可能应该看看float。TryParse或Convert.ToFloat。

其他回答

我把0.02美元放进去。有时,您需要在稍后的代码中添加“finally”(因为谁会在第一次就写出完美的代码呢?)在这些情况下,将try/catch放在循环之外突然变得更有意义了。例如:

try {
    for(int i = 0; i < max; i++) {
        String myString = ...;
        float myNum = Float.parseFloat(myString);
        dbConnection.update("MY_FLOATS","INDEX",i,"VALUE",myNum);
    }
} catch (NumberFormatException ex) {
    return null;
} finally {
    dbConnection.release();  // Always release DB connection, even if transaction fails.
}

因为如果出现错误,您只希望释放一次数据库连接(或选择您最喜欢的其他资源类型……)。

My perspective would be try/catch blocks are necessary to insure proper exception handling, but creating such blocks has performance implications. Since, Loops contain intensive repetitive computations, it is not recommended to put try/catch blocks inside loops. Additionally, it seems where this condition occurs, it is often "Exception" or "RuntimeException" which is caught. RuntimeException being caught in code should be avoided. Again, if if you work in a big company it's essential to log that exception properly, or stop runtime exception to happen. Whole point of this description is PLEASE AVOID USING TRY-CATCH BLOCKS IN LOOPS

为try/catch设置一个特殊的堆栈框架会增加额外的开销,但是JVM可能能够检测到您正在返回并优化它。

根据迭代次数的不同,性能差异可能可以忽略不计。

然而,我同意其他人的观点,把它放在循环之外会让循环体看起来更干净。

如果您希望继续处理,而不是在存在无效数字时退出,那么您将希望代码位于循环中。

你应该喜欢外面的版本而不是里面的版本。这只是规则的一个特定版本,将任何可以移动到循环外的东西移动到循环外。根据IL编译器和JIT编译器的不同,您的两个版本最终可能具有不同的性能特征,也可能没有。

另一方面,你可能应该看看float。TryParse或Convert.ToFloat。

上面没有提到的另一个方面是,每个try-catch都会对堆栈产生一些影响,这可能会对递归方法产生影响。

如果方法"outer()"调用方法"inner()"(它可能递归地调用自己),如果可能的话,尝试在方法"outer()"中找到try-catch。我们在性能类中使用的一个简单的“堆栈崩溃”示例,当try-catch在内部方法中时,在大约6400帧时失败,当它在外部方法中时,在大约11,600帧时失败。

在现实世界中,如果您正在使用Composite模式并且具有大型、复杂的嵌套结构,这可能会成为一个问题。