为什么“功能主体”成为我的应用程序的瓶颈?

时间:2018-09-27 08:28:37

标签: .net vb.net performance

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

我已经运行了Visual Studio的性能诊断程序,发现下一个类的GetHashCode函数有66%的时间在运行一个函数。

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%

由于该函数除了调用ToUpperGetHashCode函数外什么也不做,因此我很难在这里找出可以改进的地方。

您能帮我阐明一下吗?

1 个答案:

答案 0 :(得分:5)

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

  

Function Body还会显示您的总时间(以及   在功能主体中花费的时间百分比(不包括在   调用和被调用函数

但是,这并没有真正解释为什么在排除GetHashCodeToUpper的调用的情况下,在GetHashCode中花费了2/3的时间。

但是..

  

“功能主体中的高值可能表示性能瓶颈   在函数本身中”

很明显,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
相关问题