vb.net - performance implications of implementing a generic type and a delegate in a function
I wrote a serializer (to Byte Array) for dictionaries that have a string key, but an object of some sort as its value.
I've never implemented a generic type in a function or used a delegate before, so I'm a bit concerned about this being significantly slower than writing a serialization function for a specific type of Dictionary (Dictionary(Of String, MyClass) for example).
Should this code be significantly slower due to the use of the generic type or the delegate?
Public Delegate Function Serializer(Of T)(ByRef Obj As T) As Byte()
Function SerializeDictionary_String_Object(Of T)(ByRef D As Dictionary(Of String, T), ByVal S As Serializer(Of T)) As Byte()
Dim OBJ As T
For Each X In D
OBJ = X.Value
Exit For
Next
Return S(OBJ)
End Function
Here's some code that uses this:
SerializeDictionary_String_Object(Of MyClass)(MyDictionary, AddressOf MyClass.Serialize)
It works, and I could loop it and compare it to a more static Dictionary serializer, but I'm more concerned about when I start using this for a lot of different String/Object 开发者_运维问答dictionary combinations, and it'll take me a long time to write a bunch of static dictionary serializers (that's what I'm hoping to avoid in the first place)
edit: simplified intro text
No, generics were specifically designed to make code faster. Just as fast as hard-coding the types. Quicker than the alternative, using Object, since you can avoid boxing value types and don't have to cast.
A delegate call is slower than a direct method call. But it is still very, very fast. You'd have to call it a billion times to notice the difference.
Are you aware of the BinaryFormatter class? It already does this.
精彩评论