C# 三元运算符的速度是 if-else 块的两倍?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17328641/
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-10 09:11:33  来源:igfitidea点击:

Ternary operator is twice as slow as an if-else block?

c#performanceconditional-operator

提问by user1032613

I read everywhere that ternary operator is supposed to be faster than, or at least the same as, its equivalent if-elseblock.

我到处都读到三元运算符应该比它的等效if-else块更快,或者至少相同。

However, I did the following test and found out it's not the case:

但是,我做了以下测试,发现事实并非如此:

Random r = new Random();
int[] array = new int[20000000];
for(int i = 0; i < array.Length; i++)
{
    array[i] = r.Next(int.MinValue, int.MaxValue);
}
Array.Sort(array);

long value = 0;
DateTime begin = DateTime.UtcNow;

foreach (int i in array)
{
    if (i > 0)
    {
        value += 2;
    }
    else
    {
        value += 3;
    }
    // if-else block above takes on average 85 ms

    // OR I can use a ternary operator:
    // value += i > 0 ? 2 : 3; // takes 157 ms
}
DateTime end = DateTime.UtcNow;
MessageBox.Show("Measured time: " + (end-begin).TotalMilliseconds + " ms.\r\nResult = " + value.ToString());

My computer took 85 ms to run the code above. But if I comment out the if-elsechunk, and uncomment the ternary operator line, it will take about 157 ms.

我的电脑花了 85 毫秒来运行上面的代码。但是如果我注释掉if-else块,并取消注释三元运算符行,大约需要 157 毫秒。

Why is this happening?

为什么会这样?

采纳答案by Sam Harwell

To answer this question, we'll examine the assembly code produced by the X86 and X64 JITs for each of these cases.

为了回答这个问题,我们将检查由 X86 和 X64 JIT 为每种情况生成的汇编代码。

X86, if/then

X86,如果/那么

    32:                 foreach (int i in array)
0000007c 33 D2                xor         edx,edx 
0000007e 83 7E 04 00          cmp         dword ptr [esi+4],0 
00000082 7E 1C                jle         000000A0 
00000084 8B 44 96 08          mov         eax,dword ptr [esi+edx*4+8] 
    33:                 {
    34:                     if (i > 0)
00000088 85 C0                test        eax,eax 
0000008a 7E 08                jle         00000094 
    35:                     {
    36:                         value += 2;
0000008c 83 C3 02             add         ebx,2 
0000008f 83 D7 00             adc         edi,0 
00000092 EB 06                jmp         0000009A 
    37:                     }
    38:                     else
    39:                     {
    40:                         value += 3;
00000094 83 C3 03             add         ebx,3 
00000097 83 D7 00             adc         edi,0 
0000009a 42                   inc         edx 
    32:                 foreach (int i in array)
0000009b 39 56 04             cmp         dword ptr [esi+4],edx 
0000009e 7F E4                jg          00000084 
    30:             for (int x = 0; x < iterations; x++)
000000a0 41                   inc         ecx 
000000a1 3B 4D F0             cmp         ecx,dword ptr [ebp-10h] 
000000a4 7C D6                jl          0000007C 

X86, ternary

X86,三元

    59:                 foreach (int i in array)
00000075 33 F6                xor         esi,esi 
00000077 83 7F 04 00          cmp         dword ptr [edi+4],0 
0000007b 7E 2D                jle         000000AA 
0000007d 8B 44 B7 08          mov         eax,dword ptr [edi+esi*4+8] 
    60:                 {
    61:                     value += i > 0 ? 2 : 3;
00000081 85 C0                test        eax,eax 
00000083 7F 07                jg          0000008C 
00000085 BA 03 00 00 00       mov         edx,3 
0000008a EB 05                jmp         00000091 
0000008c BA 02 00 00 00       mov         edx,2 
00000091 8B C3                mov         eax,ebx 
00000093 8B 4D EC             mov         ecx,dword ptr [ebp-14h] 
00000096 8B DA                mov         ebx,edx 
00000098 C1 FB 1F             sar         ebx,1Fh 
0000009b 03 C2                add         eax,edx 
0000009d 13 CB                adc         ecx,ebx 
0000009f 89 4D EC             mov         dword ptr [ebp-14h],ecx 
000000a2 8B D8                mov         ebx,eax 
000000a4 46                   inc         esi 
    59:                 foreach (int i in array)
000000a5 39 77 04             cmp         dword ptr [edi+4],esi 
000000a8 7F D3                jg          0000007D 
    57:             for (int x = 0; x < iterations; x++)
000000aa FF 45 E4             inc         dword ptr [ebp-1Ch] 
000000ad 8B 45 E4             mov         eax,dword ptr [ebp-1Ch] 
000000b0 3B 45 F0             cmp         eax,dword ptr [ebp-10h] 
000000b3 7C C0                jl          00000075 

X64, if/then

X64,如果/那么

    32:                 foreach (int i in array)
00000059 4C 8B 4F 08          mov         r9,qword ptr [rdi+8] 
0000005d 0F 1F 00             nop         dword ptr [rax] 
00000060 45 85 C9             test        r9d,r9d 
00000063 7E 2B                jle         0000000000000090 
00000065 33 D2                xor         edx,edx 
00000067 45 33 C0             xor         r8d,r8d 
0000006a 4C 8B 57 08          mov         r10,qword ptr [rdi+8] 
0000006e 66 90                xchg        ax,ax 
00000070 42 8B 44 07 10       mov         eax,dword ptr [rdi+r8+10h] 
    33:                 {
    34:                     if (i > 0)
00000075 85 C0                test        eax,eax 
00000077 7E 07                jle         0000000000000080 
    35:                     {
    36:                         value += 2;
00000079 48 83 C5 02          add         rbp,2 
0000007d EB 05                jmp         0000000000000084 
0000007f 90                   nop 
    37:                     }
    38:                     else
    39:                     {
    40:                         value += 3;
00000080 48 83 C5 03          add         rbp,3 
00000084 FF C2                inc         edx 
00000086 49 83 C0 04          add         r8,4 
    32:                 foreach (int i in array)
0000008a 41 3B D2             cmp         edx,r10d 
0000008d 7C E1                jl          0000000000000070 
0000008f 90                   nop 
    30:             for (int x = 0; x < iterations; x++)
00000090 FF C1                inc         ecx 
00000092 41 3B CC             cmp         ecx,r12d 
00000095 7C C9                jl          0000000000000060 

X64, ternary

X64,三元

    59:                 foreach (int i in array)
00000044 4C 8B 4F 08          mov         r9,qword ptr [rdi+8] 
00000048 45 85 C9             test        r9d,r9d 
0000004b 7E 2F                jle         000000000000007C 
0000004d 45 33 C0             xor         r8d,r8d 
00000050 33 D2                xor         edx,edx 
00000052 4C 8B 57 08          mov         r10,qword ptr [rdi+8] 
00000056 8B 44 17 10          mov         eax,dword ptr [rdi+rdx+10h] 
    60:                 {
    61:                     value += i > 0 ? 2 : 3;
0000005a 85 C0                test        eax,eax 
0000005c 7F 07                jg          0000000000000065 
0000005e B8 03 00 00 00       mov         eax,3 
00000063 EB 05                jmp         000000000000006A 
00000065 B8 02 00 00 00       mov         eax,2 
0000006a 48 63 C0             movsxd      rax,eax 
0000006d 4C 03 E0             add         r12,rax 
00000070 41 FF C0             inc         r8d 
00000073 48 83 C2 04          add         rdx,4 
    59:                 foreach (int i in array)
00000077 45 3B C2             cmp         r8d,r10d 
0000007a 7C DA                jl          0000000000000056 
    57:             for (int x = 0; x < iterations; x++)
0000007c FF C1                inc         ecx 
0000007e 3B CD                cmp         ecx,ebp 
00000080 7C C6                jl          0000000000000048 

First: why is the X86 code so muchslower than X64?

第一:为什么X86代码比X64慢这么多

This is due to the following characteristics of the code:

这是由于代码的以下特点:

  1. X64 has several additional registers available, and each register is 64-bits. This allows the X64 JIT to perform the inner loop entirely using registers aside from loading ifrom the array, while the X86 JIT places several stack operations (memory access) in the loop.
  2. valueis a 64-bit integer, which requires 2 machine instructions on X86 (addfollowed by adc) but only 1 on X64 (add).
  1. X64 有几个额外的寄存器可用,每个寄存器都是 64 位的。这允许 X64 JIT 除了从i数组加载之外,完全使用寄存器执行内部循环,而 X86 JIT 在循环中放置几个​​堆栈操作(内存访问)。
  2. value是一个 64 位整数,在 X86 上需要 2 条机器指令(add后跟adc),但在 X64 上只需要 1 条机器指令(add)。

Second: why is the ternary operator slower on both X86 and X64?

第二:为什么三元运算符在 X86 和 X64 上都变慢了?

This is due to a subtle difference in the order of operations impacting the JIT's optimizer. To JIT the ternary operator, rather than directly coding 2and 3in the addmachine instructions themselves, the JIT creating an intermediate variable (in a register) to hold the result. This register is then sign-extended from 32-bits to 64-bits before adding it to value. Since all of this is performed in registers for X64, despite the significant increase in complexity for the ternary operator the net impact is somewhat minimized.

这是由于影响 JIT 优化器的操作顺序的细微差别。为了 JIT 三元运算符,而不是直接编码23add机器指令本身中,JIT 创建一个中间变量(在寄存器中)来保存结果。然后将该寄存器从 32 位符号扩展到 64 位,然后再将其添加到value. 由于所有这些都是在 X64 的寄存器中执行的,尽管三元运算符的复杂性显着增加,但净影响在某种程度上被最小化。

The X86 JIT on the other hand is impacted to a greater extent because the addition of a new intermediate value in the inner loop causes it to "spill" another value, resulting in at least 2 additional memory accesses in the inner loop (see the accesses to [ebp-14h]in the X86 ternary code).

另一方面,X86 JIT 受到的影响更大,因为在内循环中添加一个新的中间值会导致它“溢出”另一个值,从而导致内循环中至少有 2 次额外的内存访问(请参阅访问到[ebp-14h]X86 三元代码中)。

回答by Jon Skeet

EDIT: All change... see below.

编辑:所有变化......见下文。

I can't reproduce your results on the x64 CLR, but I canon x86. On x64 I can see a smalldifference (less than 10%) between the conditional operator and the if/else, but it's much smaller than you're seeing.

我无法在 x64 CLR 上重现您的结果,但我可以在 x86上重现。在 x64 上,我可以看到条件运算符和 if/else 之间的微小差异(小于 10%),但它比您看到的要小得多。

I've made the following potential changes:

我做了以下潜在的改变:

  • Run in a console app
  • Build with /o+ /debug-, and run outside the debugger
  • Run both pieces of code once to JIT them, then lots of times for more accuracy
  • Use Stopwatch
  • 在控制台应用程序中运行
  • 使用 构建/o+ /debug-,并在调试器之外运行
  • 运行两段代码一次以对它们进行 JIT,然后多次运行以提高准确性
  • Stopwatch

Results with /platform:x64(without the "ignore" lines):

结果/platform:x64(没有“忽略”行):

if/else with 1 iterations: 17ms
conditional with 1 iterations: 19ms
if/else with 1000 iterations: 17875ms
conditional with 1000 iterations: 19089ms

Results with /platform:x86(without the "ignore" lines):

结果/platform:x86(没有“忽略”行):

if/else with 1 iterations: 18ms
conditional with 1 iterations: 49ms
if/else with 1000 iterations: 17901ms
conditional with 1000 iterations: 47710ms

My system details:

我的系统详细信息:

  • x64 i7-2720QM CPU @2.20GHz
  • 64-bit Windows 8
  • .NET 4.5
  • x64 i7-2720QM CPU @2.20GHz
  • 64 位 Windows 8
  • .NET 4.5

So unlike before, I think you areseeing a real difference - and it's all to do with the x86 JIT. I wouldn't like to say exactly whatis causing the difference - I may update the post later on with more details if I can bother to go into cordbg :)

所以不像以前,我觉得你看到一个真正的区别-这一切都与x86 JIT做。我不想确切地说是什么导致了差异 - 如果我可以费心进入cordbg,我可能会在稍后更新帖子以提供更多详细信息:)

Interestingly, without sorting the array first, I end up with tests which take about 4.5x as long, at least on x64. My guess is that this is to do with branch prediction.

有趣的是,如果没有先对数组进行排序,我最终会得到大约需要 4.5 倍时间的测试,至少在 x64 上是这样。我的猜测是这与分支预测有关。

Code:

代码:

using System;
using System.Diagnostics;

class Test
{
    static void Main()
    {
        Random r = new Random(0);
        int[] array = new int[20000000];
        for(int i = 0; i < array.Length; i++)
        {
            array[i] = r.Next(int.MinValue, int.MaxValue);
        }
        Array.Sort(array);
        // JIT everything...
        RunIfElse(array, 1);
        RunConditional(array, 1);
        // Now really time it
        RunIfElse(array, 1000);
        RunConditional(array, 1000);
    }

    static void RunIfElse(int[] array, int iterations)
    {        
        long value = 0;
        Stopwatch sw = Stopwatch.StartNew();

        for (int x = 0; x < iterations; x++)
        {
            foreach (int i in array)
            {
                if (i > 0)
                {
                    value += 2;
                }
                else
                {
                    value += 3;
                }
            }
        }
        sw.Stop();
        Console.WriteLine("if/else with {0} iterations: {1}ms",
                          iterations,
                          sw.ElapsedMilliseconds);
        // Just to avoid optimizing everything away
        Console.WriteLine("Value (ignore): {0}", value);
    }

    static void RunConditional(int[] array, int iterations)
    {        
        long value = 0;
        Stopwatch sw = Stopwatch.StartNew();

        for (int x = 0; x < iterations; x++)
        {
            foreach (int i in array)
            {
                value += i > 0 ? 2 : 3;
            }
        }
        sw.Stop();
        Console.WriteLine("conditional with {0} iterations: {1}ms",
                          iterations,
                          sw.ElapsedMilliseconds);
        // Just to avoid optimizing everything away
        Console.WriteLine("Value (ignore): {0}", value);
    }
}

回答by CodeCamper

Run without debugging ctrl+F5 it seems the debugger slows down both ifs and ternary significantly but it seems it slows down the ternary operator much more.

在不调试 ctrl+F5 的情况下运行,似乎调试器显着减慢了 ifs 和三元运算的速度,但似乎它减慢了三元运算符的速度。

When I run the following code here are my results. I think the small millisecond difference is caused by the compiler optimizing the max=max and removing it but is probably not making that optimization for the ternary operator. If someone could check the assembly and confirm this it would be awesome.

当我运行以下代码时,这是我的结果。我认为微小的毫秒差异是由编译器优化 max=max 并删除它引起的,但可能没有对三元运算符进行优化。如果有人可以检查组件并确认这一点,那就太棒了。

--Run #1--
Type   | Milliseconds
Ternary 706
If     704
%: .9972
--Run #2--
Type   | Milliseconds
Ternary 707
If     704
%: .9958
--Run #3--
Type   | Milliseconds
Ternary 706
If     704
%: .9972

Code

代码

  for (int t = 1; t != 10; t++)
        {
            var s = new System.Diagnostics.Stopwatch();
            var r = new Random(123456789);   //r
            int[] randomSet = new int[1000]; //a
            for (int i = 0; i < 1000; i++)   //n
                randomSet[i] = r.Next();     //dom
            long _ternary = 0; //store
            long _if = 0;      //time
            int max = 0; //result
            s.Start();
            for (int q = 0; q < 1000000; q++)
            {
                for (int i = 0; i < 1000; i++)
                    max = max > randomSet[i] ? max : randomSet[i];
            }
            s.Stop();
            _ternary = s.ElapsedMilliseconds;
            max = 0;
            s = new System.Diagnostics.Stopwatch();
            s.Start();
            for (int q = 0; q < 1000000; q++)
            {
                for (int i = 0; i < 1000; i++)
                    if (max > randomSet[i])
                        max = max; // I think the compiler may remove this but not for the ternary causing the speed difference.
                    else
                        max = randomSet[i];
            }

            s.Stop();
            _if = s.ElapsedMilliseconds;
            Console.WriteLine("--Run #" + t+"--");
            Console.WriteLine("Type   | Milliseconds\nTernary {0}\nIf     {1}\n%: {2}", _ternary, _if,((decimal)_if/(decimal)_ternary).ToString("#.####"));
        }

回答by Shaz

I did what Jon Skeet did and ran through 1 iteration and 1,000 iterations and got a different result from both OP and Jon. In mine, the ternary is just slightly faster. Below is the exact code:

我做了 Jon Skeet 所做的并运行了 1 次迭代和 1,000 次迭代,并从 OP 和 Jon 得到了不同的结果。在我的,三元只是稍微快一点。下面是具体的代码:

static void runIfElse(int[] array, int iterations)
    {
        long value = 0;
        Stopwatch ifElse = new Stopwatch();
        ifElse.Start();
        for (int c = 0; c < iterations; c++)
        {
            foreach (int i in array)
            {
                if (i > 0)
                {
                    value += 2;
                }
                else
                {
                    value += 3;
                }
            }
        }
        ifElse.Stop();
        Console.WriteLine(String.Format("Elapsed time for If-Else: {0}", ifElse.Elapsed));
    }

    static void runTernary(int[] array, int iterations)
    {
        long value = 0;
        Stopwatch ternary = new Stopwatch();
        ternary.Start();
        for (int c = 0; c < iterations; c++)
        {
            foreach (int i in array)
            {
                value += i > 0 ? 2 : 3;
            }
        }
        ternary.Stop();


        Console.WriteLine(String.Format("Elapsed time for Ternary: {0}", ternary.Elapsed));
    }

    static void Main(string[] args)
    {
        Random r = new Random();
        int[] array = new int[20000000];
        for (int i = 0; i < array.Length; i++)
        {
            array[i] = r.Next(int.MinValue, int.MaxValue);
        }
        Array.Sort(array);

        long value = 0;

        runIfElse(array, 1);
        runTernary(array, 1);
        runIfElse(array, 1000);
        runTernary(array, 1000);

        Console.ReadLine();
    }

The output from my program:

我的程序的输出:

Elapsed time for If-Else: 00:00:00.0140543

Elapsed time for Ternary: 00:00:00.0136723

Elapsed time for If-Else: 00:00:14.0167870

Elapsed time for Ternary: 00:00:13.9418520

If-Else 的经过时间:00:00:00.0140543

三元的经过时间:00:00:00.0136723

If-Else 的经过时间:00:00:14.0167870

三元已用时间:00:00:13.9418520

Another run in milliseconds:

另一个以毫秒为单位运行:

Elapsed time for If-Else: 20

Elapsed time for Ternary: 19

Elapsed time for If-Else: 13854

Elapsed time for Ternary: 13610

If-Else 已用时间:20

三元已用时间:19

If-Else 已用时间:13854

三元已用时间:13610

This is running in 64-bit XP, and I ran without debugging.

这是在 64 位 XP 中运行的,我在没有调试的情况下运行。

Edit - Running in x86:

编辑 - 在 x86 中运行:

There's a big difference using x86. This was done without debugging on and on the same xp 64-bit machine as before, but built for x86 CPUs. This looks more like OP's.

使用 x86 有很大的不同。这是在没有像以前一样在同一台 xp 64 位机器上进行调试的情况下完成的,但它是为 x86 CPU 构建的。这看起来更像OP。

Elapsed time for If-Else: 18

Elapsed time for Ternary: 35

Elapsed time for If-Else: 20512

Elapsed time for Ternary: 32673

If-Else 已用时间:18

三元已用时间:35

If-Else 已用时间:20512

三元已用时间:32673

回答by Shaz

The assembler code generated will tell the story:

生成的汇编代码将讲述这个故事:

a = (b > c) ? 1 : 0;

Generates:

产生:

mov  edx, DWORD PTR a[rip]
mov  eax, DWORD PTR b[rip]
cmp  edx, eax
setg al

Whereas:

然而:

if (a > b) printf("a");
else printf("b");

Generates:

产生:

mov edx, DWORD PTR a[rip]
mov eax, DWORD PTR b[rip]
cmp edx, eax
jle .L4
    ;printf a
jmp .L5
.L4:
    ;printf b
.L5:

So the ternary canbe shorter and faster simply due to using fewer instructions and no jumps ifyou are looking for true/false. If you use values other than 1 and 0, you will get the same code as an if/else, for example:

因此,由于使用较少的指令并且如果您正在寻找真/假,则三元可以更短和更快。如果您使用 1 和 0 以外的值,您将获得与 if/else 相同的代码,例如:

a = (b > c) ? 2 : 3;

Generates:

产生:

mov edx, DWORD PTR b[rip]
mov eax, DWORD PTR c[rip]
cmp edx, eax
jle .L6
    mov eax, 2
jmp .L7
.L6:
    mov eax, 3
.L7:

Which is the same as the if/else.

这与 if/else 相同。

回答by Matthew Steeples

Looking at the IL generated, there are 16 less operations in that than in the if/else statement (copying and pasting @JonSkeet's code). However, that doesn't mean it should be a quicker process!

查看生成的 IL,其中的操作比 if/else 语句少 16 个(复制和粘贴 @JonSkeet 的代码)。但是,这并不意味着它应该是一个更快的过程!

To summarise the differences in IL, the if/else method translates to pretty much the same as the C# code reads (performing the addition within the branch) whereas the conditional code loads either 2 or 3 onto the stack (depending on the value) and then adds it to value outside of the conditional.

总结 IL 中的差异,if/else 方法转换为与 C# 代码读取几乎相同(在分支内执行加法),而条件代码将 2 或 3 加载到堆栈上(取决于值)和然后将其添加到条件之外的值中。

The other difference is the branching instruction used. The if/else method uses a brtrue (branch if true) to jump over the first condition, and an unconditional branch to jump from the first out of the if statement. The conditional code uses a bgt (branch if greater than) instead of a brtrue, which could possibly be a slower comparison.

另一个区别是使用的分支指令。if/else 方法使用 brtrue(如果为真则分支)来跳过第一个条件,并使用无条件分支从 if 语句的第一个跳出。条件代码使用 bgt(如果大于则分支)而不是 brtrue,这可能是比较慢的比较。

Also (having just read about branch prediction) there may be a performance penalty for the branch being smaller. The conditional branch only has 1 instruction within the branch but the if/else has 7. This would also explain why there's a difference between using long and int, because changing to an int reduces the number of instructions in the if/else branches by 1 (making the read-ahead less)

此外(刚刚阅读了关于分支预测的内容)可能会因分支较小而导致性能损失。条件分支在分支中只有 1 条指令,而 if/else 有 7 条指令。这也可以解释为什么使用 long 和 int 之间存在差异,因为更改为 int 会将 if/else 分支中的指令数量减少 1 (减少预读)

回答by Eren Ers?nmez

The difference really doesn't have much to do with if/else vs ternary.

差异实际上与 if/else 与三元没有太大关系。

Looking at the jitted disassemblies (I won't repaste here, pls see @280Z28's answer), it turns out you're comparing apples and oranges. In one case, you create two different +=operations with constant values and which one you pick depends on a condition, and in the other case, you create a +=where the value to adddepends on a condition.

看看 jitted 的拆卸(我不会在这里重复,请参阅@280Z28 的答案),结果您正在比较 apples 和 oranges。在一种情况下,您+=使用常量值创建两个不同的操作,您选择哪一个取决于条件,而在另一种情况下,您创建一个+=其中要添加取决于条件。

If you want to truly compare if/else vs ternary, this would be a more fair comparison (now both will be equally "slow", or we could even say ternary is a bit faster):

如果你想真正比较 if/else 与三元,这将是一个更公平的比较(现在两者都将同样“慢”,或者我们甚至可以说三元更快一些):

int diff;
if (i > 0) 
    diff = 2;
else 
    diff = 3;
value += diff;

vs.

对比

value += i > 0 ? 2 : 3;

Now the disassembly for the if/elsebecomes as shown below. Note that this is bit worse than the ternary case, since it quit using the registers for the loop variable(i) as well.

现在拆解if/else如下图所示。请注意,这比三元情况更糟,因为它也停止使用循环变量 ( i)的寄存器。

                if (i > 0)
0000009d  cmp         dword ptr [ebp-20h],0 
000000a1  jle         000000AD 
                {
                    diff = 2;
000000a3  mov         dword ptr [ebp-24h],2 
000000aa  nop 
000000ab  jmp         000000B4 
                }
                else
                {
                    diff = 3;
000000ad  mov         dword ptr [ebp-24h],3 
                }
                value += diff;
000000b4  mov         eax,dword ptr [ebp-18h] 
000000b7  mov         edx,dword ptr [ebp-14h] 
000000ba  mov         ecx,dword ptr [ebp-24h] 
000000bd  mov         ebx,ecx 
000000bf  sar         ebx,1Fh 
000000c2  add         eax,ecx 
000000c4  adc         edx,ebx 
000000c6  mov         dword ptr [ebp-18h],eax 
000000c9  mov         dword ptr [ebp-14h],edx 
000000cc  inc         dword ptr [ebp-28h] 

回答by Ken Kin

Edit:

编辑:

Added an example which can be done with the if-else statement but not the conditional operator.

添加了一个示例,该示例可以使用 if-else 语句完成,但不能使用条件运算符。



Before the answer, please have a look of [Which is faster?] on Mr. Lippert's blog. And I think Mr. Ers?nmez's answeris the most correct one here.

在回答之前,请先看看[哪个更快?] 在 Lippert 先生的博客上。我认为Ers?nmez 先生的回答是最正确的。

I'm trying to mention something we should keep in mind with a high-level programming language.

我试图提到一些我们应该记住的高级编程语言。

First off, I've never heard that the conditional operator is supposed to be faster or the equally performance with if-else statement in C?.

首先,我从来没有听说过条件运算符应该更快,或者与C 中的if-else 语句具有相同的性能.

The reason is simple that what if there's no operation with the if-else statement:

原因很简单,如果没有 if-else 语句的操作会怎样:

if (i > 0)
{
    value += 2;
}
else
{
}

The requirement of conditional operator is there must be a valuewith either side, and in C? it also requires that both side of :has the same type. This just makes it different from the if-else statement. Thus your question becomes a question asking how the instruction of the machine code is generated so that the difference of performance.

条件运算符的要求是两边都必须有一个值,而在 C? 它还要求的两侧:具有相同的类型。这只是使它与 if-else 语句不同。因此,您的问题变成了询问机器代码的指令如何生成从而导致性能差异的问题。

With the conditional operator, semantically it is:

使用条件运算符,语义上是:

Whatever the expression is evaluated, there's a value.

无论表达式如何计算,都有一个值。

But with if-else statement:

但是使用 if-else 语句:

If the expression is evaluated to true, do something; if not, do another thing.

如果表达式被评估为真,做一些事情;如果没有,请做另一件事。

A value is not necessarily involved with if-else statement.Your assumption is only possible with optimization.

if-else 语句不一定涉及值。您的假设只有通过优化才有可能。

Another example to demonstrate the difference between them would be like the following:

演示它们之间差异的另一个示例如下所示:

var array1=new[] { 1, 2, 3 };
var array2=new[] { 5, 6, 7 };

if(i>0)
    array1[1]=4;
else
    array2[2]=4;

the code above compiles, however, replace if-else statement with the conditional operator just won't compile:

上面的代码可以编译,但是,用条件运算符替换 if-else 语句就不会编译:

var array1=new[] { 1, 2, 3 };
var array2=new[] { 5, 6, 7 };
(i>0?array1[1]:array2[2])=4; // incorrect usage 

The conditional operator and the if-else statements are conceptual the same when you do the same thing, it possibly even faster with the conditional operator in C, since C is more closer to the assembly of the platform.

当你做同样的事情时,条件运算符和 if-else 语句在概念上是相同的,在 C 中使用条件运算符可能会更快,因为 C 更接近平台的程序集。



For the original code you provided, the conditional operator is used in a foreach-loop, which would mess things up to see the difference between them. So I'm proposing the following code:

对于您提供的原始代码,在 foreach 循环中使用了条件运算符,这会使事情变得混乱以查看它们之间的区别。所以我提出以下代码:

public static class TestClass {
    public static void TestConditionalOperator(int i) {
        long value=0;
        value+=i>0?2:3;
    }

    public static void TestIfElse(int i) {
        long value=0;

        if(i>0) {
            value+=2;
        }
        else {
            value+=3;
        }
    }

    public static void TestMethod() {
        TestConditionalOperator(0);
        TestIfElse(0);
    }
}

and the following are two version of the IL of optimized and not. Since they are long, I'm using an image to show, the right hand side is the optimized one:

以下是优化和未优化的两个版本的IL。由于它们很长,我使用图像来显示,右侧是优化的:

(Click to see full-size image.) hSN6s.png

(点击查看全尺寸图像。) hSN6s.png

In both version of code, the IL of the conditional operator looks shorter than the if-else statement, and there still is a doubt of the machine code finally generated. The following are the instructions of both method, and the former image is non-optimized, the latter is the optimized one:

在这两个版本的代码中,条件运算符的IL看起来比if-else语句短,最终生成的机器码仍然存在疑问。以下是两种方法的使用说明,前一张为非优化图,后一张为优化后的一张:

  • Non-optimized instructions:(Click to see full-size image.) ybhgM.png

  • Optimized instructions:(Click to see full-size image.) 6kgzJ.png

  • 非优化说明:(点击查看全尺寸图片。) ybhgM.png

  • 优化说明:(点击查看大图) 6kgzJ.png

In the latter, the yellow block is the code only executed if i<=0, and the blue block is when i>0. In either version of instructions, the if-else statement is shorter.

在后者中,黄色块是仅在 if 时执行的代码i<=0,蓝色块是 when i>0。在任一版本的指令中,if-else 语句都较短。

Note that, for different instructions, the [CPI] is not necessarily the same. Logically, for the identical instruction, more instructions cost longer cycle. But if the instruction fetching time and pipe/cache were also take into account, then the real total time of execution depends on the processor. The processor can also predict the branches.

请注意,对于不同的指令,[ CPI] 不一定相同。从逻辑上讲,对于相同的指令,指令越多,周期越长。但是如果同时考虑取指令时间和管道/缓存,那么实际执行的总时间取决于处理器。处理器还可以预测分支。

Modern processors have even more cores, things can be more complex with that. If you were an Intel processor user, you might want to have a look of [Intel? 64 and IA-32 Architectures Optimization Reference Manual].

现代处理器具有更多内核,因此事情可能会更加复杂。如果您是 Intel 处理器用户,您可能想看看 [ Intel? 64 和 IA-32 架构优化参考手册]。

I don't know if there was a hardware-implemented CLR, but if yes, you probably get faster with conditional operator because the IL is obviously lesser.

我不知道是否有硬件实现的 CLR,但如果有,使用条件运算符可能会更快,因为 IL 显然更小。

Note: All the machine code are of x86.

注:所有机器码均为x86。

回答by Alexey Novikov

In the following code if/else seems to be roughly 1.4 times faster than the ternary operator. However, I found that introducing a temporary variable decreases the ternary operator's run time approximately 1.4 times:

在下面的代码中,if/else 似乎比三元运算符快 1.4 倍。但是,我发现引入临时变量将三元运算符的运行时间减少了大约 1.4 倍:

If/Else: 98 ms

Ternary: 141 ms

Ternary with temp var: 100 ms

如果/否则:98 毫秒

三元:141 毫秒

三元与临时变量:100 毫秒

using System;
using System.Diagnostics;

namespace ConsoleApplicationTestIfElseVsTernaryOperator
{
    class Program
    {
        static void Main(string[] args)
        {
            Random r = new Random(0);
            int[] array = new int[20000000];
            for (int i = 0; i < array.Length; i++)
            {
                array[i] = r.Next(int.MinValue, int.MaxValue);
            }
            Array.Sort(array);
            long value;
            Stopwatch stopwatch = new Stopwatch();

            value = 0;
            stopwatch.Restart();
            foreach (int i in array)
            {
                if (i > 0)
                {
                    value += 2;
                }
                else
                {
                    value += 3;
                }
                // 98 ms
            }
            stopwatch.Stop();
            Console.WriteLine("If/Else: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");

            value = 0;
            stopwatch.Restart();
            foreach (int i in array)
            {
                value += (i > 0) ? 2 : 3; 
                // 141 ms
            }

            stopwatch.Stop();
            Console.WriteLine("Ternary: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");

            value = 0;
            int tempVar = 0;
            stopwatch.Restart();
            foreach (int i in array)
            {
                tempVar = (i > 0) ? 2 : 3;
                value += tempVar; 
                // 100ms
            }
            stopwatch.Stop();
            Console.WriteLine("Ternary with temp var: " + stopwatch.ElapsedMilliseconds.ToString() + " ms");

            Console.ReadKey(true);
        }
    }
}

回答by Ravindra Sinare

Too many great answers but I found something interesting, very simple changes make the impact. After making below change, to execute if-else and ternary operator it will take same time.

太多很好的答案,但我发现了一些有趣的东西,非常简单的变化会产生影响。进行以下更改后,执行 if-else 和三元运算符需要相同的时间。

instead of writing below line

而不是写在下面

value +=  i > 0 ? 2 : 3;

I used this,

我用过这个

int a =  i > 0 ? 2 : 3;
value += a;

One of the below answer also mention that what is bad way to write ternary operator.

以下答案之一还提到编写三元运算符的错误方法。

I hope this will help you to write ternary operator, instead of thinking of which one is better.

我希望这能帮助您编写三元运算符,而不是考虑哪个更好。

Nested Ternary Operator:I found nested ternary operator and multiple if else block will also takes same time to execute.

嵌套三元运算符:我发现嵌套三元运算符和多个 if else 块也需要相同的时间来执行。