Microsoft(和许多开发人员)声称SqlDataReader。GetOrdinal方法与使用命名查找(例如)相比,提高了从DataReader检索值的性能。读者("ColumnName")。问题是,如果处理小的分页记录集,真正的性能差异是什么?在整个代码中查找和引用有序索引的额外开销值得吗?
Microsoft建议不要在循环中调用GetOrdinal。
这将包括对字符串索引器的间接调用。
你可以在循环的顶部使用GetOrdinal,将序数放入数组中,并将数组中的索引设置为const或枚举(根本不使用GetOrdinal),或者将GetOrdinal用于具有描述性名称的单个变量。
只有当你的集合很小时,我才会认为这是一个过早的优化。
任何差异都会被维护开销所抵消。
如果你有那么多的数据,它会产生明显的差异,我建议你在客户端代码中有太多的数据。或者当考虑使用序数而不是名称时
是和不是。
如果你正在处理大量的数据,那么你肯定会从使用序数而不是列名中受益。
否则,保持简单、易读和更安全——并坚持使用列名。
只在需要时优化
我为SqlDataReader创建了一个包装器,它以列名作为键将序数存储在字典中。
它给了我有序的性能提升,同时保持代码更具可读性,并且如果有人改变了从存储过程返回的列顺序,则不太可能中断。
Friend Class DataReader
Implements IDisposable
Private _reader As SqlDataReader
Private _oridinals As Dictionary(Of String, Integer)
Private Shared _stringComparer As StringComparer = StringComparer.OrdinalIgnoreCase 'Case in-sensitive
Public Sub New(reader As SqlDataReader)
Me._reader = reader
Me.SetOrdinals()
End Sub
Private Sub SetOrdinals()
Me._oridinals = New Dictionary(Of String, Integer)(_stringComparer)
For i As Integer = 0 To Me._reader.FieldCount - 1
Me._oridinals.Add(Me._reader.GetName(i), i)
Next
End Sub
Public Function Read() As Boolean
Return Me._reader.Read()
End Function
Public Function NextResult() As Boolean
Dim value = Me._reader.NextResult()
If value Then
Me.SetOrdinals()
End If
Return value
End Function
Default Public ReadOnly Property Item(name As String) As Object
Get
Return Me._reader(Me.GetOrdinal(name))
End Get
End Property
Public Function GetOrdinal(name As String) As Integer
Return Me._oridinals.Item(name)
End Function
Public Function GetInteger(name As String) As Integer
Return Me._reader.GetInt32(Me.GetOrdinal(name))
End Function
Public Function GetString(ordinal As Integer) As String
Return Me._reader.GetString(ordinal)
End Function
Public Function GetString(name As String) As String
Return Me._reader.GetString(Me.GetOrdinal(name))
End Function
Public Function GetDate(name As String) As Date
Return Me._reader.GetDateTime(Me.GetOrdinal(name))
End Function
Public Function GetDateNullable(name As String) As Nullable(Of Date)
Dim o = Me._reader.GetValue(Me.GetOrdinal(name))
If o Is System.DBNull.Value Then
Return Nothing
Else
Return CDate(o)
End If
End Function
Public Function GetDecimal(name As String) As Decimal
Return Me._reader.GetDecimal(Me.GetOrdinal(name))
End Function
Public Function GetBoolean(name As String) As Boolean
Return Me._reader.GetBoolean(Me.GetOrdinal(name))
End Function
Public Function GetByteArray(name As String) As Byte()
Return CType(Me._reader.GetValue(Me.GetOrdinal(name)), Byte())
End Function
Public Function GetBooleanFromYesNo(name As String) As Boolean
Return Me._reader.GetString(Me.GetOrdinal(name)) = "Y"
End Function
'Disposable Code
End Class