我将在服务器应用程序上编写一组方法,这些方法接收从TCP套接字接收的消息,对它们进行编码/解码,然后对它们进行加密/解密。
考虑到消息被定义为特殊类型,每个类型都有自己的一组属性和总长度,我需要选择以下解决方案之一: 1.创建使用泛型的方法,例如Encode<T>(...) where T : IMessage,然后为每种类型的消息实现编码器/解码器,并让ResolveEncoder<T>为所需的消息选择编码器。2.创建使用任何类型的消息的方法,只要它实现了IMessage,例如Encode(IMessage message),并使用System.Reflection来确定我需要了解的所有信息。
我对解决方案#2更感兴趣,因为它使我的代码小了30倍。但是,我担心属性的持续反射是否会影响性能。现在由于我完成这个项目的时间有限,我不能真正的“实验”。
我将非常感谢任何个人经验或与基准测试的链接,了解这两种解决方案的性能如何下降。
发布于 2012-04-18 11:55:16
反射可以足够快。但是需要正确地实现。
反射性能-
快速和轻量功能
typeof
Object.GetType
typeof == Object.GetType
Type equivalence APIs (including typehandle operator overloads)
get_Module
get_MemberType
Some of the IsXX predicate APIs
New token/handle resolution APIs in the .NET Framework 2.0代价高昂的函数
GetXX APIs (MethodInfo, PropertyInfo, FieldInfo, and so on)
GetCustomAttributes
Type.InvokeMember
Invoke APIs (MethodInfo.Invoke, FieldInfo.GetValue, and so on)
get_Name (Name property)
Activator.CreateInstanceSource - Dodge Common Performance Pitfalls to Craft Speedy Applications
MethodInfo可以加速- Improving performance reflection , what alternatives should I consider
好的链接:
How costly is .NET reflection?
http://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces
发布于 2012-04-18 11:38:15
现在,由于我完成这个项目的时间有限,我不能真正地“实验”。
那么,您真正的约束不是性能,而是您可以在给定的时间约束内编写、测试和调试的代码。假设你声称反射版本要小30倍,这听起来就是你应该倾向于的。
然而,有五点:
我怀疑30倍的估计是正确的,smaller.
PropertyInfo来缓解这种情况,而且你不能通过reflection.
发布于 2012-04-18 11:35:06
泛型是在编译时绑定的,其性能与普通类型一样好。反思将会付出巨大的代价。
https://stackoverflow.com/questions/10202365
复制相似问题