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.
Now as I'm time limited to finish the project, I can't really "experiment".
Then your real constraint is not performance, but rather which can you code and test and debug in the given time constraint. Supposing that your claim that the reflection version is 30x smaller, it sounds like that's what you should lean towards.
However, five points:
PropertyInfo
s and what not that you load by reflection.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With