248

我到处都读到三元运算符应该比它的等效块更快,或者至少与其相同ifelse

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

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());

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

为什么会这样?

4

10 回答 10

380

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

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,三元

    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,如果/那么

    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,三元

    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 

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

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

  1. X64 有几个额外的寄存器可用,每个寄存器都是 64 位的。这允许 X64 JIT 完全使用寄存器执行内部循环i,而不是从数组加载,而 X86 JIT 在循环中放置几个​​堆栈操作(内存访问)。
  2. value是一个 64 位整数,在 X86 上需要 2 条机器指令(add后跟adc),但在 X64 上只需要 1 条(add)。

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

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

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

于 2013-06-26T22:01:14.470 回答
63

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

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

我进行了以下潜在更改:

  • 在控制台应用程序中运行
  • 构建/o+ /debug-并在调试器之外运行
  • 运行两段代码一次 JIT,然后多次运行以获得更高的准确性
  • 采用Stopwatch

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

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

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

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

我的系统详情:

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

所以与以前不同的是,我认为您看到了真正的不同——这一切都与 x86 JIT 有关。我不想确切地说是什么导致了这种差异 - 如果我可以费心进入cordbg,我可能会在稍后更新帖子,提供更多细节:)

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

代码:

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);
    }
}
于 2013-06-26T19:30:48.113 回答
44

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

查看 jitted disassemblies(我不会在这里重新粘贴,请参阅@280Z28 的答案),事实证明您是在比较 apples 和 oranges。在一种情况下,您使用常量值创建两个不同的+=操作,您选择的操作取决于条件,而在另一种情况下,您创建一个要添加+=的值取决于条件的操作。

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

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

对比

value += i > 0 ? 2 : 3;

现在反汇编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] 
于 2013-06-27T08:25:42.093 回答
9
于 2013-06-27T14:45:00.947 回答
7

我做了 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();
    }

我的程序的输出:

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

三进制经过的时间:00:00:00.0136723

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

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

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

If-Else 的经过时间:20

三元经过时间:19

If-Else 的经过时间:13854

三元的经过时间:13610

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

编辑 - 在 x86 中运行:

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

If-Else 的经过时间:18

三元经过时间:35

If-Else 的经过时间:20512

三元的经过时间:32673

于 2013-06-26T20:16:32.183 回答
5

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

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

生成:

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

然而:

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

生成:

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:

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

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

生成:

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:

这与 if/else 相同。

于 2013-06-26T21:15:38.410 回答
4

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

当我运行以下代码时,这是我的结果。我认为微小的毫秒差异是由编译器优化 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

代码

  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("#.####"));
        }
于 2013-06-26T19:57:12.510 回答
4

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

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

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

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

于 2013-06-26T21:24:03.200 回答
1

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

如果/否则: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);
        }
    }
}
于 2015-10-14T12:21:40.940 回答
0

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

而不是写在下面

value +=  i > 0 ? 2 : 3;

这个我用过

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

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

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

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

于 2020-03-10T10:14:29.740 回答