快速整数ABS功能

编程入门 行业动态 更新时间:2024-10-28 01:19:28
本文介绍了快速整数ABS功能的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 int X = a-b; int d = Math.Abs(X);

我非常确定.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功能

本文发布于:2023-11-26 04:38:28,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1632653.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:整数   快速   功能   ABS

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!