I've had some great feedback from Buu Nguyen author of the Fasterflect library. He supplied the feedback below as well as some sample code, which I have incorporated into the code base.
Buu Nguyen says:
Fasterflect only speeds up invocation operations, not query (aka lookup) operations. In fact, query operations in Fasterflect are convenient wrapper for .NET reflection, so using them will cause the code to run slower.
Suggested usage: avoid query operations if you don’t really need them; move the GetProperties out of each iteration because it is the same for all methods and thus makes it hard to see the performance difference when using Fasterflect.
The delegates should be reused instead of being regenerated every time – the latter will make the code run even slower than the normal Fasterflect API.
Suggested usage: use a dictionary to cache the generated
The main change to the code was to cache the call to type.GetProperties(). So instead of calling the GetProperties() method directly a call is made to a caching component which ensures that the GetProperties() call is only made once per type.
Also, as Buu has suggested, the calls for generating the delegate setters and getters are now cached into a static dictionary as well.
Test Methods (2-4 using cached call to type.GetProperties() ):
- Long Hand - No reflection.
- Initial code - normal reflection
- FasterFlect m1 - Uses the FasterFlect library
- FasterFlect m2 – Uses the FasterFlect library’s delegates approach
Results
So here are the results (over 1 million object trims):
Long Hand Trim | 00:00:01.4150000 |
Initial code | 00:00:08.8280000 |
Fasterflect m1 | 00:00:04.8190000 |
Fasterflect m2 | 00:00:02.9920000 |
Ok, now we are seeing Fasterflect perform nearly twice as fast as reflection and about 3 times as fast when using the delegate method of Fasterflect.
It also appears that the delegate method of Fasterflect is only about twice as slow as the long hand trim.
It also appears that the delegate method of Fasterflect is only about twice as slow as the long hand trim.