Array bounds check efficiency in .net 4 and above

后端 未结 4 988
离开以前
离开以前 2020-12-05 06:19

I\'m interested in how efficient low-level algorithms can be in .net. I would like to enable us to choose to write more of our code in C# rather than C++ in the future, but

4条回答
  •  一个人的身影
    2020-12-05 07:01

    The bounds check won't matter because:

    • The bounds check consists of a cmp/jae instruction pair, which is fused into a single micro-op on modern CPU architectures (the term is "macro-op fusion"). Compare and branch is very highly optimized.

    • The bounds check is a forward branch, which will be statically predicted to be not-taken, also reducing the cost. The branch will never be taken. (If it ever is taken, an exception will throw anyway, so the mispredict cost becomes utterly irrelevant)

    • As soon as there is any memory delay, speculative execution will queue up many iterations of the loop, so the cost of decoding the extra instruction pair almost disappears.

    Memory access will likely be your bottleneck, so the effect micro-optimizations like removing bounds checks will disappear.

提交回复
热议问题