With my Quickly Trim all your model's string properties post causing quite a stir (2 comments), I have decided to post a follow up and actually test the speed.
For the actual benchmarking I used a slightly modified version of this nice little class http://www.yoda.arachsys.com/csharp/Benchmark.cs, which I found from this page http://www.yoda.arachsys.com/csharp/benchmark.html
I tested 4 different methods that use reflection to trim all the string properties on an object and the 'long hand' method that does not use reflection at all.
- Long Hand - No reflection.
- Initial code - with the GetIndexParameters call removed (not needed)
- Initial code with linq – Initial code but using linq to select the properties to process
- TypeDescriptor– used the TypeDescriptor class to get the property list
- FasterFlect m1 - Uses the FasterFlect library
- FasterFlect m2 – Uses the FasterFlect library’s delegates approach
ResultsSo here are the results (over 1 million object trims):
|Long Hand Trim||00:00:01.4220000|
|Initial code with linq||00:00:10.7270000|
Surprised? I was. Firstly, the refection code varied from 7 - 14 times slower then the direct code, this wasn't a surprise more of a reminder that you really need to be careful when using reflection in your code base.
I knew my initial code would perform better then trying to filter for properties before doing the work. Filtering the properties first using linq or any other means, basically results in another loop over the properties on the object. So the more properties you have on your object the worst this method will perform.
But I was quite suprised with the TypeDescriptor. I had hopes that this would perform better then my initial code, as according to the documentation this method actually caches the meta data about objects. I am suspicious I haven’t used it to its full potential…
The other surprise was that the delegate method in fasterflect is actually slower then the normal method. Again, someone may well point out how to implement this better. The other note is that fasterflect was only able to achieve an 80% reduction. I was hoping for more.
Anyway interesting stuff, if someone has another fast method to achieve the same results let me know I’ll take it for a test drive.