c# - 有没有更有效的方法来计算减法表达式的绝对值

标签 c# .net performance subtraction absolute-value

这个问题几乎说明了一切。目前,我正在使用 Math.Abs​​(a - b) 来计算减法表达式的绝对值,例如 5 - 1010 - 5 都返回 5

是否有更有效的方法来做到这一点,或者这是最有效的方法?

最佳答案

在您确切知道问题出在哪里之前,请不要对代码进行微观优化。

您可以自己实现一个,并将其设为内联函数,以减少函数调用的成本,方法是使用 MethodImplAttribute .

如果您使用 Int32 值并且您的输入恰好不是边界值,那么您可以使用此

Abs(x) = (x ^ (x >> 31)) - (x >> 31)

但我建议您忘记这一切,分析您的应用程序,您会发现真正的问题不在调用 Math.Abs​​ 中,您应该始终首先使代码可读,然后进行调整性能问题之后你证明它们确实是性能问题!

Programmers waste enormous amounts of time thinking about, or worrying about, the speed of noncritical parts of their programs, and these attempts at efficiency actually have a strong negative impact when debugging and maintenance are considered. We should forget about small efficiencies, say about 97% of the time: premature optimization is the root of all evil. Yet we should not pass up our opportunities in that critical 3%.
(DonaldKnuth's paper "StructuredProgrammingWithGoToStatements")

阅读this

关于c# - 有没有更有效的方法来计算减法表达式的绝对值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27372979/

相关文章:

c# - OnBackButtonPressed 不触发 Xamarin 表单

c# - 在集合初始值设定项中使用条件

c# - 列出磁盘上的所有分区

.net - 为什么 New() 在我继承的控件上触发两次? (winforms)

java - List.toArray(Object[]) 性能

c++ - 虚拟方法会使应用程序变慢,但它们可以加快链接速度吗?

performance - 与 Java 相比,Scala 的性能如何?

c# - 最大化远程桌面 ActiveX 控件

c# - 如何使用 LINQ 获取 id 的列表作为 int

c# - 在 C# 中访问重写的公共(public)属性