250

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

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-else chunk, and uncomment the ternary operator line, it will take about 157 ms.

Why is this happening?

admdrew
  • 3,790
  • 4
  • 27
  • 39
WSBT
  • 33,033
  • 18
  • 128
  • 133
  • 96
    First thing to fix: don't use `DateTime` to measure performance. Use `Stopwatch`. Next, time rather longer - that's a very short time to measure. – Jon Skeet Jun 26 '13 at 19:19
  • 2
    I tried to loop it 10 more times, with a seed of 42, got 849 ms and 1564 ms. I don't think it's an error on the measurement part. – WSBT Jun 26 '13 at 19:21
  • 49
    Use a seed when you create the `Random` object, so that it always gives the same sequence. If you test different code with different data, you can very well see differences in performance. – Guffa Jun 26 '13 at 19:21
  • 12
    Did you also try compiling/running it in release mode with compiler optimizations turned on, and without the debugger attached? – Chris Sinclair Jun 26 '13 at 19:22
  • 2
    Using a console app rather than what looks like a WinForms app would be a good idea, too... – Jon Skeet Jun 26 '13 at 19:23
  • 2
    Why did you sort your array? What results do you get if you don't? – Larry OBrien Jun 26 '13 at 19:23
  • 2
    SO-Help: [You should only ask practical, answerable questions based on actual problems that you face](http://stackoverflow.com/help/dont-ask), sowhat problem are you trying to solve due to performance? – Erik Philips Jun 26 '13 at 19:23
  • 7
    @LarryOBrien: Interesting take. I just did a quick LINQPad test and get very different results with the array sorted or not. In fact, with it sorted I reproduce the same speed difference reported. Removing the sort also removes the time difference. – Chris Sinclair Jun 26 '13 at 19:26
  • 1
    There are many possible compiler optimizations for your code that will affect its run time, and skew the results. (The array being sorted for one, checking the sign of the value, always adding either of two numbers) – NominSim Jun 26 '13 at 19:27
  • FWIW, there's no difference under Mono on Mac: larryobrien$ csharp tnry.cs Elapsed 00:00:00.0637078 larryobrien$ csharp tnry.cs Elapsed 00:00:00.0631514 – Larry OBrien Jun 26 '13 at 19:28
  • 39
    The point here is that performance testing microoptimizations is *hard*. Virtually all of the things you're observing in your result are related to bugs in your testing code, not differences in the meaningful code. When you fix those listed here, there will be more, I can assure you. The moral of the story, don't bother with microoptimizations or trying to test them in the first place. If the code is actually hard to measure it means it's not slow enough to be a bottleneck; ignore it. – Servy Jun 26 '13 at 19:29
  • 4
    I strongly suspect that it has to do with this answer here: http://stackoverflow.com/q/11227809/109122. (Which is probably the highest rated question and answer on SO.) – RBarryYoung Jun 26 '13 at 19:34
  • @RBarryYoung Don't think so. It's a sorted array in *both* tests. He's never comparing sorted runs with unsorted runs. – Servy Jun 26 '13 at 19:36
  • @Servy Look at his/her response to Larry OBrien above. – RBarryYoung Jun 26 '13 at 19:38
  • @ChrisSinclair Based on Skeet's answer, the reason that the unsorted case shows no time difference is because the branch mispredictions are so expensive that they are probably hiding the minute difference. – Mysticial Jun 27 '13 at 00:36
  • Try running it using `(i<0)?(value+=2):(value+=3)`. – AJMansfield Jun 27 '13 at 16:38
  • @280Z28's answer is the best--no contest--but you should always consider eliminating the need for a conditional when it comes to performance. JavaScript is loosely typed, so you can change `value += i > 0 ? 2 : 3;` to `value += (i > 0) + 2;`. How about the assembly for that, @280Z28? – hector-j-rivas Feb 13 '14 at 16:00

10 Answers10

380

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

X86, if/then

    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

    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

    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

    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 much slower than 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 i from the array, while the X86 JIT places several stack operations (memory access) in the loop.
  2. value is a 64-bit integer, which requires 2 machine instructions on X86 (add followed by adc) but only 1 on X64 (add).

Second: why is the ternary operator slower on both X86 and 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 2 and 3 in the add machine 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.

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).

Sam Harwell
  • 97,721
  • 20
  • 209
  • 280
  • 20
    The compiler might as well expand out the ternary into an if-else. – dezfowler Jun 26 '13 at 22:49
  • Thanks for the assembly dumps. In fact, what I saw was very different as ternary op created four stackbased temporaries to hold 64bit longs, while ifelse just used registers. I wonder why the resulting assembly differs. Did you get your dumps from VS Native debugger? Have you used ngen or any other similar tool? – quetzalcoatl Jun 26 '13 at 22:54
  • @quetzalcoatl I used the VS debugger, but explicitly unchecked the option to "Suppress JIT optimization on module load" – Sam Harwell Jun 27 '13 at 00:51
  • 1
    @dez It doesn't make much of a difference here, where `value` is a local variable. However, if `value` were in any way visible to another thread (e.g. by being a field of the class), the order of operations would be key - in the if/else code `i` is read before `value`, but in the ternary operator case `value` is read before `i`. – Sam Harwell Jun 27 '13 at 00:52
  • 13
    Note that x86 is only slower when using _ternary_ -- it is as equally fast as x64 when using _if/else_. So the question to answer is: "why is the X86 code so much slower than X64 when using the ternary operator?". – Eren Ersönmez Jun 27 '13 at 07:54
  • 19
    Surely there's no good reason for this and MS should 'fix' it - as Ternary is effectively just a shorter syntax for if/else?! You certainly wouldn't expect to pay a performance penalty anyway. – niico Jun 27 '13 at 10:29
  • 6
    @niico there's nothing to 'fix' about the ternary operator. it's usage in this case just happens to cause a different register allocation. In a different case, it might be faster than if/else, as I tried to explain in my answer. – Eren Ersönmez Jun 27 '13 at 12:41
  • 1
    so you're saying the ternary expression is effectively asking to do something a bit different than an if/then would in this case? Rather than it just being implemented differently to do something identical? – niico Jun 27 '13 at 17:54
  • 7
    @ErenErsönmez: Sure there's something to fix. The optimizer team can carefully analyze the two cases and find a way to cause the ternary operator, in this case, to be just as fast as if-else. Of course, such a fix may be infeasible or too expensive. – Brian Jun 27 '13 at 18:46
  • 2
    @KenKin: I think you're underestimating the cost of "simple" fixes. "Optimized in the same way" may not be as simple as you'd think, and may in fact sometimes result in worse performance. Further, even tiny changes have high costs due to investigating and testing requirements. Whether those costs are *too* high I don't know, but there's probably a huge number of similar minor optimization suggestions like this, many of which are wrong, duplicated, or have subtle and non-obvious problems. – Brian Jun 27 '13 at 20:56
  • @Brian: Sure, if what you meant is not only the equality of particular cases between the two. What I want to say is, they are fundamentally different things, and only in some way conceptually equivalent. – Ken Kin Jun 27 '13 at 21:05
  • Is this the case with other languages too? I mean of course it will but did they(developers of new languages) kept that in mind and tried to improve this? – Daksh Gargas Nov 26 '18 at 04:05
63

EDIT: All change... see below.

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

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

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

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):

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

So unlike before, I think you are seeing a real difference - and it's all to do with the x86 JIT. I wouldn't like to say exactly what is causing the difference - I may update the post later on with more details if I can bother to go into 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.

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);
    }
}
Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • Still needs statistical verification, you know, for science – Ast Derek Jun 26 '13 at 19:33
  • 31
    So the question everyone is still dying to know, is *why* there is even a tiny difference. – Brad M Jun 26 '13 at 19:33
  • I ran your code unmodified, here's my result: 1 iteration: 85 ms, 156 ms. – WSBT Jun 26 '13 at 19:34
  • Which is run first seems to identify the "winner" after JIT. – user7116 Jun 26 '13 at 19:34
  • 1
    @BradM: Well the IL will be different, and any difference at all could do all kinds of things by the time it's JIT-compiled and then the CPU itself has done nasty stuff to it. – Jon Skeet Jun 26 '13 at 19:35
  • @BradM Noise on the system. His machine is running other things, the CPU won't have 100% constant performance, GC allocations running around there, other arbitrary background tasks going on by the runtime (even if you did disable every other application on the machine), etc. – Servy Jun 26 '13 at 19:35
  • 1
    @user7116: The "1 iteration" version isn't terribly useful though - it's the 1000 iteration (or 100 if you don't want to wait as long) version which is more important. – Jon Skeet Jun 26 '13 at 19:35
  • 1
    @Servy: I'm not sure it's noise - it seems to be pretty repeatable, even if I switch round the order of the tests. – Jon Skeet Jun 26 '13 at 19:37
  • @JonSkeet actually I think 20 million is already a fairly large number, so I'd say running 1 iteration is more or less enough... Looking at your own result, 1 iteration seems to provide the same ratio of difference as the 1000 iterations version. – WSBT Jun 26 '13 at 19:37
  • 1
    @user1032613: If you want to decide that, then fine - but I wouldn't trust a difference that small to give anything really meaningful. Given that I've already provided the code to run it for longer, why not do so? – Jon Skeet Jun 26 '13 at 19:38
  • @user1032613: I've included my system details here - they may well be *very* relevant. – Jon Skeet Jun 26 '13 at 19:39
  • @user1032613: Another point is that if you take the attitude that 20 million is already a bit number, I'd say that 156ms is already a small amount of time to iterate over 20 million numbers. I strongly suspect that the number of applications where this loop would be the bottleneck is very small. – Jon Skeet Jun 26 '13 at 19:40
  • @Jonskeet I will run your code later tonight when I get to a faster computer. Currently with 1 iteration, using your unmodified code, I still get 85ms/156ms as my result. I will update my result later, for science. – WSBT Jun 26 '13 at 19:41
  • 4
    @JonSkeet FYI. ran your code, exactly like you explained. 19s vs 52s in x86, and 19s vs 21s in x64. – Eren Ersönmez Jun 26 '13 at 19:42
  • @JonSkeet: in a best of 5x1000 (using different random seeds though), I got a "push" in who was faster based on which ran first. – user7116 Jun 26 '13 at 19:44
  • @ErenErsönmez: Interesting - that's provoked me to *explicitly* select x86 on my box, which has then caused a change. Will edit. – Jon Skeet Jun 26 '13 at 19:46
  • Also to note: I get the same results in both VS2010/4.0 and VS2012/4.5. – Eren Ersönmez Jun 26 '13 at 19:49
  • 5
    @user1032613: I *can* now reproduce your results. See my edit. Apologies for doubting you before - it's amazing the difference a change in architecture can make... – Jon Skeet Jun 26 '13 at 19:50
  • 1
    @JonSkeet If I change the `long` types to `int` in your methods, then the performance difference disappears. So I think this might be related to the register allocation issue that was identified here: http://stackoverflow.com/q/8928403/201088. – Eren Ersönmez Jun 26 '13 at 19:55
  • 1
    @ErenErsönmez: That would be interesting... Adding a `try/catch` block into this sample code seems to slow the `if/else` version down to nearly the same as the conditional operator version. – Jon Skeet Jun 26 '13 at 19:56
  • 1
    Now that's curious. I think that this would be a perfect candidate to disassemble to final binaries and check what actually that try/catch has changed in that if/else.. I find it hard to image what could get injected. Not even boxing. Uh. Forgive me for asking. Debug or Release? In debug, I actually can imagine some extra checks.. – quetzalcoatl Jun 26 '13 at 20:03
  • @quetzalcoatl: Release, as per "/o+ /debug-" - I'm installing the Windows SDK so I can dive into the JITted code. – Jon Skeet Jun 26 '13 at 20:04
  • Ah, sorry, didnt notice that switches – quetzalcoatl Jun 26 '13 at 20:05
  • 1
    On my x86 the if-else (26ms) generates about 60b with (a?JbbbbbJcccccd) structure, while ternary version (60ms) generates about 90bytes of machine code with (aaaa?JbbbJcccdddddd) structure and uses twice as much memory for local variables. The AA and DD are common loop parts, the ?J is conditional branch that selects B or C, and the J is unconditional that jumps to D. The amount of letters is just to visually show the lengths. The ternary prepares the value using first or second set of locals, then performs common addition, the ifelse uses one set of locals and has whole code duplicated. – quetzalcoatl Jun 26 '13 at 20:42
  • 1
    However, observing the assembly code, I am do not sure if I properly generated optimized version.. It looks.. so verbose that I actually **doubt** I managed to get it optimized, but times match your observations: a bit over 2x difference – quetzalcoatl Jun 26 '13 at 20:45
  • ..and adding try-catches wrapping whole methods changed nothing. I didnt tried adding it to the body, I think that would change the case too much. I tried reducing `long`->`int` and indeed the both examples run faster: 23 and 26ms instead of 26 and 60ms. Codes produced by both ifelse and ternary were much simplier due to datatype change, but overall structure remained the same. Well.. sorry for overloading comments, but I'm curios to hear from someone who gets 'properly optimized' version - does it look similar? – quetzalcoatl Jun 26 '13 at 21:07
  • @quetzalcoatl i can reproduce that adding try-catch around the for loops slows down the if/else version in x86. – Eren Ersönmez Jun 26 '13 at 21:40
  • @JonSkeet: I've also upvoted this answer for *wouldn't like to say exactly what is causing the difference*, since I belive which is irrelevant with the language. I've never heard the conditional operator is **guaranteed** to be equally or even faster of the performance with if-else in c#, do you? – Ken Kin Jun 27 '13 at 19:26
  • 1
    @KenKin: No, there's definitely no guarantee - but I'd have liked to have understood things a little better :) – Jon Skeet Jun 27 '13 at 19:35
  • 1
    Your answer just explains the results, but doesn't really answers the question : why it happens – BЈовић Jun 29 '13 at 07:17
  • 3
    @BЈовић: Indeed. It started off as not being able to reproduce it at all, but evolved over time. It doesn't give the reason, but I thought it was still useful information (e.g. the x64 vs x86 difference) which is why I left it up. – Jon Skeet Jun 29 '13 at 07:19
44

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

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 add depends on a condition.

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):

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

vs.

value += i > 0 ? 2 : 3;

Now the disassembly for the if/else becomes 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 (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] 
Eren Ersönmez
  • 38,383
  • 7
  • 71
  • 92
  • 5
    How about emphasizing **comparing apples and oranges**? – Ken Kin Jun 27 '13 at 20:40
  • 6
    Well, I wouldn't actually say that it's comparing apples and oranges. The both variants have the same _semantics_, so the optimizer _could_ try both optimization variants and choose whichever is more efficient in _either_ case. – Vlad Jul 02 '13 at 21:13
  • I did the test as you suggested: introduced another variable `diff`, but ternary is still a lot slower - not at all what you said. Did you do the experiment before posting this "answer"? – WSBT Mar 20 '14 at 18:24
9

Edit:

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


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

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♯.

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

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

The requirement of conditional operator is there must be a value with 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.

With the conditional operator, semantically it is:

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

But with if-else statement:

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.

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:

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.


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:

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:

(Click to see full-size image.) 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:

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

  • Optimized instructions: (Click to see full-size image.) 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.

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.

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].

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.

Note: All the machine code are of x86.

Ken Kin
  • 4,503
  • 3
  • 38
  • 76
7

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:

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

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

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

Edit - Running in 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.

Elapsed time for If-Else: 18

Elapsed time for Ternary: 35

Elapsed time for If-Else: 20512

Elapsed time for Ternary: 32673

Community
  • 1
  • 1
Shaz
  • 1,376
  • 8
  • 18
5

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 can be shorter and faster simply due to using fewer instructions and no jumps if you 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:

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.

4

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.

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.

--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("#.####"));
        }
CodeCamper
  • 6,609
  • 6
  • 44
  • 94
4

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!

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.

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.

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)

Matthew Steeples
  • 7,858
  • 4
  • 34
  • 49
1

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: 98 ms

Ternary: 141 ms

Ternary with temp var: 100 ms

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);
        }
    }
}
Community
  • 1
  • 1
0

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.

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.

Ravindra Sinare
  • 675
  • 1
  • 9
  • 25