Question

This is a serializer I've been working on that serializes datarow's into objects based on some mapped property attributes. I read a number of posts related to using [Delegate].CreateDelegate to increase speed - so I gave that a try. It seems to have gained some performance increase, but minimal at that (even after an initial looping of all object types to cache all possible property info objects and such). The mapped property info's just have an alternate DB column name that can be assigned, because we don't have complete control over all column names I use. It also only grabs properties I want to map.

Right now, the serialization of approx. 1500 objects with an average of 13 properties per object, and an average of 3 object within each of the 1500 parent object (as children) also being populated with an average of 13 properties a piece - boast these times for my comparison:

manually setting a property.Name = row.Item("columnName")
785 ms

p.SetValue
1490 ms

GetSetMethod.Invoke
1585 ms

[Delegate].CreateDelegate
1285 ms

Can anyone suggest something more I can do to increase performance??

  Friend Class DataSerializer(Of T As Class)

        Private Shared MappedPropertiesCache As New Dictionary(Of Type, PropertyInfo())
        Private Shared MappedColumnNameCache As New Dictionary(Of Type, List(Of String))

        Private Shared ActionCache As New Dictionary(Of String, Action(Of T, Object))

        Friend Shared Function SerializeDataRow(ByVal row As DataRow) As T

            Dim target As Object = Activator.CreateInstance(GetType(T))

            Dim targetType As Type = GetType(T)

            AnalyzeMappedCache(target, targetType)

            Dim index As Integer = 0

            Dim mappedColumns As List(Of String) = MappedColumnNameCache.Item(targetType)

            'iterate through target object properties
            For Each p As PropertyInfo In MappedPropertiesCache.Item(targetType)

                If row.Table.Columns.Contains(mappedColumns.Item(index)) Then


                    '' SLOW
                    'p.SetValue(target, CheckDbNull(row.Item(mappedColumns.Item(index))), Nothing)


                    '' SLOWER
                    'Dim methodInfo As MethodInfo = p.GetSetMethod()

                    'methodInfo.Invoke(target, New Object() {CheckDbNull(row.Item(mappedColumns.Item(index)))})



                    ''FASTER THAN PREVIOUS TWO, BUT STILL SLOW


                    'Dim key As String = String.Format("{0}:{1}", target.GetType.FullName, p.Name)

                    'If Not ActionCache.ContainsKey(key) Then

                    '    Dim methodAction As Action(Of T, Object) = MagicMethod(p.GetSetMethod())

                    '    ActionCache.Add(key, methodAction)

                    'End If

                    'Dim param As Object = CheckDbNull(row.Item(mappedColumns.Item(index)))

                    'If Not param Is Nothing Then

                    '    ActionCache(key)(target, param)

                    'End If

                End If

                index = index + 1

            Next

            Return target

        End Function


        Private Shared Function MagicMethod(method As MethodInfo) As Action(Of T, Object)
            ' First fetch the generic form
            Dim genericHelper As MethodInfo = GetType(DataSerializer(Of T)).GetMethod("MagicMethodHelper", BindingFlags.[Static] Or BindingFlags.NonPublic)

            ' Now supply the type arguments
            Dim constructedHelper As MethodInfo = genericHelper.MakeGenericMethod(GetType(T), method.GetParameters()(0).ParameterType)

            ' Now call it. The null argument is because it's a static method.
            Dim ret As Object = constructedHelper.Invoke(Nothing, New Object() {method})

            ' Cast the result to the right kind of delegate and return it
            Return DirectCast(ret, Action(Of T, Object))
        End Function

        Private Shared Function MagicMethodHelper(Of TTarget As Class, TParam)(method As MethodInfo) As Action(Of TTarget, Object)
            ' Convert the slow MethodInfo into a fast, strongly typed, open delegate
            Dim func As Action(Of TTarget, TParam) = DirectCast([Delegate].CreateDelegate(GetType(Action(Of TTarget, TParam)), method), Action(Of TTarget, TParam))

            ' Now create a more weakly typed delegate which will call the strongly typed one
            Dim ret As Action(Of TTarget, Object) = Sub(target As TTarget, param As Object) func(target, CType(param, TParam))
            Return ret
        End Function

        Private Shared Sub AnalyzeMappedCache(ByVal target As Object, ByVal targetType As Type)

            'this assumes the target object inherits from BaseProperties
            If Not MappedPropertiesCache.ContainsKey(targetType) Then

                Dim props As PropertyInfo() = target.GetMappedProperties()

                Dim mappedColumnNameList As New List(Of String)

                For Each prop As PropertyInfo In props

                    mappedColumnNameList.Add(CType(prop.GetCustomAttributes(GetType(DTO_POMGMT.MappedProperty), True).FirstOrDefault, DTO_POMGMT.MappedProperty).ColumnName)

                Next

                MappedColumnNameCache.Add(targetType, mappedColumnNameList)

                MappedPropertiesCache.Add(targetType, props)

            End If

        End Sub

        'check for a dbnull value of any object type returned from database
        Private Shared Function CheckDbNull(ByVal obj As Object) As Object

            Return If(obj Is DBNull.Value, Nothing, obj)

        End Function

    End Class
Was it helpful?

Solution

I would suggest that you take a look at FastMember, either directly, or just borrow and adapt the code. In particular (switching a little to C#):

var accessor = TypeAccessor.Create(targetType); 
foreach(PropertyInfo p in MappedPropertiesCache.Item(targetType))
{
    ...
    accessor[target, p.Name] = ... // newValue
    ...
}

Alternatively, take a look at how something like dapper-dot-net handles member-wise assignment.

As a side note: a static dictionary is not thread-safe, and you might want to be careful accessing that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top