嵌套或没有嵌套,如果块?嵌套

2023-09-03 05:24:42 作者:奶味甜酥

我在想,如果在C#中使用IFS时有性能上的差异,以及它们嵌套与否。这里有一个例子:

I was wondering if there is a performance difference when using ifs in C#, and they are nested or not. Here's an example:

if(hello == true) {
    if(index == 34) {
        DoSomething();
    }
}

这是快于或慢于这样的:

Is this faster or slower than this:

if(hello == true && index == 34) {
    DoSomething();
}

任何想法?

推荐答案

大概是编译器足够聪明生成相同或非常相似code,这两个版本。除非性能真的是一个关键因素,为您的应用程序,我会自动选择第二个版本,为了code可读性。

Probably the compiler is smart enough to generate the same, or very similar code, for both versions. Unless performance is really a critical factor for your application, I would automatically choose the second version, for the sake of code readability.