Login | Register   
RSS Feed
Download our iPhone app
Browse DevX
Sign up for e-mail newsletters from DevX


Get Drunk on the Power of Reflection.Emit : Page 3

With Reflection.Emit, you can add dynamic typing to your C# applications and enter a strange new world.

Thinking about Performance
I know what you're thinking: Building types dynamically is interesting, but it must be an absolute pig, performance-wise. You're right. Sort of. Reflection has a reputation for poor performance that's well-deserved in certain areas. But remember that dynamically creating a new type is a one-time cost. Once the type is built, it's compiled into an assembly just like any other type in .NET.

The process of copying prototype objects, however, incurs an ongoing performance penalty. Table1 shows the three different methods of instantiating dynamic types and, just for comparison, I also timed the creation of the baseclass using the new operator. Not surprisingly, using the new operator is the fastest. But instantiating dynamic types using reflection wasn't too far behind. The prototype pattern ended up way behind the reflection-based approach, as deserialization proved to be the bottleneck.

Table 1. Hydration is the pig. When creating new instances of dynamic types, serialization ends up being the biggest performance penalty.

Approach Objects created/second *
Reflection.Activator 708,160
Hydration (Subclass) 33,483
Hyrdration (Adapter) 18,928
New Operator 3,160,493

*My desktop has PentiumIV, and 1GB of RAM.

You should still consider these numbers with some perspective. In absolute terms, creating 18,000 objects per second isn't too bad—even if it is two orders of magnitude slower than using the new operator. And there are ways to mitigate even these costs. Depending on the specifics of your application, you could build a factory class that copies prototypes on a low-priority worker thread, building up a cache of objects for when they're needed.

Moderation in All Things
This is not idiomatic C#, not yet anyway. But the platform is still young, and the ability to dynamically create new types is one thing setting .NET apart from Java. After all, it took the C++ community years to discover the true power of templates. Maybe, over the next few years, we'll all be taking advantage of the dynamic typing power of the .NET framework.

Eric McMullen is a director at Falstaff Solutions, a Denver-based consulting house which specializes in data-centric .NET applications. Check out Falstaff's Web site at www.falstaffsolutions.com.
Comment and Contribute






(Maximum characters: 1200). You have 1200 characters left.