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

后端 未结 10 987
无人及你
无人及你 2020-11-30 16:20

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 di

10条回答
  •  无人及你
    2020-11-30 16:57

    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)

提交回复
热议问题