Hacker News new | comments | show | ask | jobs | submit login
C# ternary operator is twice as slow as an if-else block? (stackoverflow.com)
10 points by anon1385 1484 days ago | hide | past | web | 2 comments | favorite



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


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.




Guidelines | FAQ | Support | API | Security | Lists | Bookmarklet | DMCA | Apply to YC | Contact

Search: