System.Reflection vs Generics - performance
c#, generics, reflection
Solution
Reflection can be fast enough. But need to be implemented correctly.
Reflection Performance -
Fast and Light Functions
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
Costly Functions
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.CreateInstance
Source - Dodge Common Performance Pitfalls to Craft Speedy Applications
MethodInfo can be speed up - Improving performance reflection , what alternatives should I consider
Good links: How costly is .NET reflection? http://www.codeproject.com/Articles/18450/HyperDescriptor-Accelerated-dynamic-property-acces
Problem
I'm about to write a set of methods on a server application that take messages received from TCP socket, encode/decode them, and encrypt/decrypt them. Considering messages are defined as special types, each with its own set of properties and total length, I need to opt for one of the following solutions: 1. Make methods that use generics, such as `Encode<T>(...) where T : IMessage` and then implement encoder/decoder for each type of message and have `ResolveEncoder<T>` that would pick encoder for wanted message or 2. Make method that uses any type of message, as long as it implements `IMessage`, such as `Encode(IMessage message)`, and use System.Reflection to determine everything I need to know about it. I'm more interested in doing solution #2 as it makes my code 30 times smaller. However, I'm worried whether constant reflection of properties will hit the performance. Now as I'm time limited to finish the project, I can't really "experiment". I would be grateful for any personal experiences or links with benchmarks on how performance falls with either of solutions.