C# ?:操作员与。If 语句性能

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/547249/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 07:41:38  来源:igfitidea点击:

?: Operator Vs. If Statement Performance

c#.netperformanceif-statementoperators

提问by Jon

I've been trying to optimize my code to make it a little more concise and readable and was hoping I wasn't causing poorer performance from doing it. I think my changes might have slowed down my application, but it might just be in my head. Is there any performance difference between:

我一直在尝试优化我的代码,使其更加简洁和可读,并希望这样做不会导致性能下降。我认为我的更改可能会减慢我的应用程序,但它可能只是在我的脑海中。之间是否有任何性能差异:

Command.Parameters["@EMAIL"].Value = email ?? String.Empty;

and

Command.Parameters["@EMAIL"].Value = (email == null) ? String.Empty: email;

and

if (email == null)
{
    Command.Parameters["@EMAIL"].Value = String.Empty
}
else
{
    Command.Parameters["@EMAIL"].Value = email
}

My preference for readability would be the null coalescing operator, I just didn't want it to affect performance.

我对可读性的偏好是空合并运算符,我只是不希望它影响性能。

采纳答案by PhilChuang

IMHO, optimize for readability and understanding - any run-time performance gains will likely be minimal compared to the time it takes you in the real-world when you come back to this code in a couple months and try to understand what the heck you were doing in the first place.

恕我直言,针对可读性和理解进行优化 - 与在现实世界中花费的时间相比,当您在几个月内返回此代码并尝试了解您到底是什么时,任何运行时性能提升都可能是最小的首先做。

回答by Frederik Gheysels

I suspect there won't be any performance difference.

我怀疑不会有任何性能差异。

Next to that, I wonder why you would have any concerns of favoring one statement over the other in this case ? I mean: the performance impact (if there should be any), would be minimal. IMHO, this would be a kind of micro-optimization, and it shouldn't be worth the effort.
I would choose the statement that is most readable, most clear, and not worry about performance since it would be of minimal influence (in this case).

除此之外,我想知道为什么你会担心在这种情况下支持一种陈述而不是另一种?我的意思是:性能影响(如果应该有的话)将是最小的。恕我直言,这将是一种微观优化,不值得付出努力。
我会选择最易读、最清晰且不担心性能的语句,因为它的影响最小(在这种情况下)。

回答by Chris Ballance

Almost no significant performance difference in this case.

在这种情况下几乎没有显着的性能差异。

When the performance difference is negligible, it is all about readable code.

当性能差异可以忽略不计时,一切都与可读代码有关

回答by casperOne

You are trying to micro-optimizehere, and that's generally a big no-no. Unless you have performance analytics which are showing you that this is an issue, it's not even worth changing.

您试图在这里进行微优化,这通常是一个很大的禁忌。除非您的性能分析表明这是一个问题,否则它甚至不值得更改。

For general use, the correct answer is whatever is easier to maintain.

对于一般用途,正确的答案是更容易维护的。

For the hell of it though, the IL for the null coalescing operator is:

尽管如此,空合并运算符的 IL 是:

L_0001: ldsfld string ConsoleApplication2.Program::myString
L_0006: dup 
L_0007: brtrue.s L_000f
L_0009: pop 
L_000a: ldsfld string [mscorlib]System.String::Empty
L_000f: stloc.0 

And the IL for the switch is:

开关的 IL 是:

L_0001: ldsfld string ConsoleApplication2.Program::myString
L_0006: brfalse.s L_000f
L_0008: ldsfld string ConsoleApplication2.Program::myString
L_000d: br.s L_0014
L_000f: ldsfld string [mscorlib]System.String::Empty
L_0014: stloc.0 

For the null coalescing operator, if the value is null, then six of the statements are executed, whereas with the switch, four operations are performed.

对于空合并运算符,如果值为null,则执行 6 条语句,而对于switch,则执行 4 条操作。

In the case of a not nullvalue, the null coalescing operator performs four operations versus five operations.

在非null值的情况下,空合并运算符执行四次操作与五次操作。

Of course, this assumes that all IL operations take the same amount of time, which is not the case.

当然,这是假设所有 IL 操作花费相同的时间,但事实并非如此。

Anyways, hopefully you can see how optimizing on this micro scale can start to diminish returns pretty quickly.

不管怎样,希望你能看到在这个微观尺度上的优化是如何开始迅速减少回报的。

That being said, in the end, for most cases whatever is the easiest to read and maintain in this case is the right answer.

话虽如此,最后,对于大多数情况,在这种情况下最容易阅读和维护的就是正确答案。

If you find you are doing this on a scale where it proves to be inefficient (and those cases are few and far between), then you should measure to see which has a better performance and then make that specific optimization.

如果您发现这样做的规模被证明是低效的(而且这种情况很少见),那么您应该衡量哪个具有更好的性能,然后进行特定的优化。

回答by Brian

I think my changes might have slowed down my application, but it might just be in my head.

我认为我的更改可能会减慢我的应用程序,但它可能只是在我的脑海中。

Unless you are actually measuringperformance, it's all in your head and idle speculation.

除非你真的在衡量性能,否则这一切都在你的脑海中,只是在胡思乱想。

(Not to pick on you in particular, but it is so disappointing to see question after question about performance micro-optimizations (as well as many of the answers) that do not contain the word "measure".)

(不是特别挑你,但看到一个又一个关于性能微优化的问题(以及许多答案)不包含“度量”一词,真是令人失望。)

回答by Brian

Its a Question of whether machine level code is efficient or Human Readable Code. As we making it more Readable to us, it makes machine to do Complex interpret the code and vice versa...

这是机器级代码是高效还是人类可读代码的问题。当我们使它对我们更具可读性时,它使机器对代码进行复杂的解释,反之亦然......

回答by Brian

For discussion sake... if/then/else runs just as fast as the ?: ternary operation as fast as a single level switch/case statement.

为了讨论...... if/then/else 的运行速度与 ?: 三元运算一样快,与单级 switch/case 语句一样快。

Here are some performance benchmarks with the C# code.

以下是 C# 代码的一些性能基准测试。

It's only when you start getting 2-3 levels deep in case statements that performance starts to be severely impacted. That is, something like this ridiculous example:

只有当您开始深入 2-3 个级别的 case 语句时,性能才开始受到严重影响。也就是说,就像这个荒谬的例子:

switch (x % 3)
    {
        case 0:
            switch (y % 3)
            {
                case 0: total += 3;
                    break;
                case 1: total += 2;
                    break;
                case 2: total += 1;
                    break;
                default: total += 0;
                    break;
            }
            break;
        case 1:
            switch (y % 3)
            {
                case 0: total += 3;
                    break;
                case 1: total += 2;
                    break;
                case 2: total += 1;
                    break;
                default: total += 0;
                    break;
            }
            break;
    case 2:
            switch (y % 3)
            {
                case 0: total += 3;
                    break;
                case 1: total += 2;
                    break;
                case 2: total += 1;
                    break;
                default: total += 0;
                    break;
            }
            break;
    default:
        switch (y % 3)
        {
            case 0: total += 3;
                break;
            case 1: total += 2;
                break;
            case 2: total += 1;
                break;
            default: total += 0;
                break;
        }
        break;
    }