快速整数ABS功能 [英] Fast integer ABS function

查看:128
本文介绍了快速整数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功能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆