

C# ternary operator is twice as slow as an if-else block? - anon1385
http://stackoverflow.com/a/17331230

======
jimrandomh
Basically, the optimizer failed to notice that

    
    
        (long)(c?a:b)
    

can be turned into

    
    
        (c?(long)a:(long)b)
    

And that since a and b are literals, the cast to long is free in the latter
case, but costs two instructions and a register in the former case.

Note that this is very much compiler-specific (the person asking the question
didn't say which compiler he was using), and I did not get the same slowdown
in the Mono compiler (with or without LLVM).

------
cocoflunchy
I think the accepted answer should be Eren Ersönmez's.

Comparing

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

Is not the same as

    
    
        value += i > 0 ? 2 : 3;
    

Quoting the answer:

    
    
        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.

