[英]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. 我为具有字符串键但值作为某种对象的字典编写了一个序列化程序(到Byte Array)。
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). 我以前从未在函数中实现泛型类型,也从未使用过委托,因此我有点担心这比为特定类型的Dictionary(例如Dictionary(Of String,MyClass))编写序列化函数要慢得多。 )。
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) 它有效,我可以循环使用它并将其与更静态的Dictionary序列化程序进行比较,但是我更担心何时将它用于许多不同的String / Object字典组合,这将花费我很长时间写一堆静态字典序列化器(这是我首先要避免的东西)
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? 您知道BinaryFormatter类吗? It already does this.
它已经做到了。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.