Web developer from Sydney Australia. Currently using asp.net, mvc where possible.

Tuesday, May 18, 2010

Quickly Trim all model's Properties - Reflection Vrs Fasterflect

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() ):
    1. Long Hand - No reflection.
    2. Initial code - normal reflection
    3. FasterFlect m1 - Uses the FasterFlect library
    4. 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.
Download the source code.

Long Hand code





Property Cache Helper


Initial code






FasterFlect Method #1


FasterFlect Method #2



2 comments:

InnomaxMediaLLP said...

It shows a lot of interesting facts and admiring content. The topic has the nature of simplicity but the article has a big impact. It is simple but knowledgeable. This is a kind of blog that is very rare to hunt online. I appreciate the blogger for the knowledge shared.
Web developer

Unknown said...

Hello There. I found your blog using msn. This is an extremely well written article. I will make sure to bookmark it and return to read more of your useful information. Thanks for the post.

I will definitely comeback.

Mechanical Seals