Activator::CreateInstance performance for more than 16 types == baaaaad

I stumbled upon this earlier this year, but I didn’t have the time to blog about it then. Since I was just doing some more tuning around the area of code where I applied this technique I figured I’d do a quick write up on it in the hopes that it may benefit someone else out there.

If you’re doing a lot of dynamic type instantiation, as one would do in a Object Relational Mapping framework for example, and you are using Activator::CreateInstance you are suffering a severe penalty if you’re instantiating more than 16 distinct types. Why? Because Activator::CreateInstance uses a cache internally that speeds up type instantiation, but it’s only capable of caching for 16 types max. So how can you speed this up? Well Haibo Luo has some great information and statistics on the subject and also provides several approaches you can use to optimize the situation. Reflection+Emit results in the best overall performance, but Dynamic Methods in .NET 2.0 come in a very close second and are a little easier to deal with.

Leave a Reply