微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

.net – 为什么“功能体”瓶颈我的应用程序?

我正在开发的应用程序运行得太慢了.

我已经运行了Visual Studio性能诊断程序,并发现一个单独的函数在66%的时间运行,即以下类的GetHashCode函数.

Public Class Identifier

    Public Property Name As String

    Public Overrides Function GetHashCode() As Integer
        Return Name.toupper().GetHashCode()
    End Function

    Public Overrides Function Equals(other As Object) As Boolean
        Dim otherIdentifier = TryCast(other,Identifier)
        If otherIdentifier Is nothing Then
            Return False
        Else
            Return String.Equals(Name,otherIdentifier.Name,StringComparison.InvariantCultureIgnoreCase)
        End If
    End Function
End Class

让我更加困惑的是,在“被调用功能”面板中,我读到了,在经历的包容时间方面:

> System.String.toupper():0.61%
> System.String.GetHashCode():0.21%
>功能体:66.67%

由于函数除了调用toupper和GetHashCode函数之外什么都不做,我很难搞清楚我在这里可以改进什么.

你能帮我解释一下吗?

我对VS性能诊断不是很熟悉.但是 here是关于功能体的内容.

Function Body also shows you the total amount of time (and the
percentage of time) spent in the function body excluding time spent in
calling and called functions

但它并没有真正解释为什么在排除对toupper和GetHashCode的调用时,在GetHashCode中花费了2/3的时间.

然而..

“High values in Function Body may indicate a performance bottleneck
within the function itself”

很明显,toupper总是必须为它必须比较的每个字符串创建一个新字符串.如果你这样做了数百万次,你就会有很高的内存压力并且GC会启动.这就是为什么我会使用StringComparer:

Public Overrides Function GetHashCode() As Integer
    Return StringComparer.InvariantCultureIgnoreCase.GetHashCode(Name)
End Function

您也可以在Equals中使用它

Public Overrides Function Equals(other As Object) As Boolean
   Dim otherIdentifier = TryCast(other,Identifier)
   If otherIdentifier Is nothing Then Return False
   Return StringComparer.InvariantCultureIgnoreCase.Equals(Name,otherIdentifier.Name)
End Function

原文地址:https://www.jb51.cc/vb/255301.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐