.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
由于该函数除了调用and函数什么都不做GetHashCode
,我很难弄清楚我可以在这里改进什么。
你能帮我解释一下吗?
解决方案
我对 VS 性能诊断不是很熟悉。但是这里提到了关于Function Body的一些内容。
Function Body
还显示在函数体中花费的总时间(和时间百分比),不包括调用和被调用函数所花费的时间
但这并不能真正解释为什么 2/3 的时间花在GetHashCode
调用ToUpper
和GetHashCode
被排除在外。
然而..
“函数体中的高值可能表明函数本身存在性能瓶颈”
这很明显,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
推荐阅读
- python - Keras acc 和 val_acc 在训练期间很高,但预测非常糟糕
- php - 我无法从一页到另一页获取价值...给我一些想法
- laravel - Laravel 收集第二个结果集关系始终为空
- macos - Gtk.jl 入门示例按钮问题
- python - PySide2.QtWidgets.QxxxxLayout.addWidget 用错误的参数类型调用
- c - 三元运算是在编译时执行的吗?
- mysql - 将表记录连接到嵌套 JSON
- flutter - 如何使用 Flutter 检查 iOS/Android 上是否启用了暗模式?
- c# - 如何与 SQL 数据库共享 c# 代码
- python - 我想根据选择字段填充 Many2one 字段