我非常确定.NET不会进行内联.那么,我该做if()还是还有其他一些鲜为人知的技巧?
I am pretty sure that .NET doesn't do inlining. So, will I do if(), or is there some other less-known trick?
推荐答案JIT在某些情况下执行内联.我不知道它是否内联Math.Abs ...但是您是否已验证这实际上是性能问题?在您知道需要进行微优化之前,请先进行以下评估:
The JIT performs inlining in some circumstances. I don't know whether it inlines Math.Abs or not... but have you verified that this is actually a performance problem for you? Don't micro-optimize until you know that you need to, and then measure the performance gain from something like:
int d = X > 0 ? X : -X;验证它确实值得.
正如Anthony所指出的,以上内容(通常)不适用于int.MinValue,就像-int.MinValue == int.MinValue一样,而Math.Abs将抛出OverflowException.您也可以使用检查的算术在直接C#中强制执行此操作:
As noted by Anthony, the above won't (normally) work for int.MinValue, as -int.MinValue == int.MinValue, whereas Math.Abs will throw an OverflowException. You can force this in the straight C# as well using checked arithmetic:
int d = X > 0 ? X : checked(-X);更多推荐
快速整数ABS功能
发布评论