首页 > 解决方案 > 为什么“功能体”会成为我的应用程序的瓶颈?

问题描述

我正在开发的应用程序运行速度太慢。

我运行了 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

更让我困惑的是,在“调用函数”面板中,我读到了经过的包含时间:

ToUpper由于该函数除了调用and函数什么都不做GetHashCode,我很难弄清楚我可以在这里改进什么。

你能帮我解释一下吗?

标签: .netvb.netperformance

解决方案


我对 VS 性能诊断不是很熟悉。但是这里提到了关于Function Body的一些内容。

Function Body还显示在函数体中花费的总时间(和时间百分比),不包括调用和被调用函数所花费的时间

但这并不能真正解释为什么 2/3 的时间花在GetHashCode调用ToUpperGetHashCode被排除在外。

然而..

“函数体中的高值可能表明函数本身存在性能瓶颈”

这很明显,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

推荐阅读