Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How create High Performance .NET classes using reflection?

Ok, so we all know Reflecttion is many time less performant than "newing" a class instance, and in many cases this is just fine depending on the application requirements.

QUESTION: How can we create high performance .NET classes using a late binding (Reflection) strategy.

I have an existing requirement that demands class instances be created using reflection (CreateInstance), but performance is critical. In my situation I am creating instances for every incoming SMS Message in our application. During production this could easily be over a million per day.

I would like to hear and share some ideas on how to create .NET classes without directly referencing the classes in code, for example using Reflection. I was also thinking if there is a way to somehow cache a class Factory that can improve the "Creation" time

like image 223
Raiford Avatar asked Jul 10 '09 21:07

Raiford


People also ask

Is .NET reflection slow?

It's common knowledge that reflection in . NET is slow, but why is that the case? This post aims to figure that out by looking at what reflection does under-the-hood.

Does .NET core support reflection?

Yes, it is. Many reflection-intensive libraries work just fine. There are some API differences that authors might need to adjust their code for, but it pretty much works the same.

Why is reflection typically considered slow in C#?

Reflection is slower Because it involves types that are dynamically resolved, certain Java virtual machine optimizations can not be performed.

Why do we use reflection in C#?

Reflection provides objects (of type Type) that describe assemblies, modules, and types. You can use reflection to dynamically create an instance of a type, bind the type to an existing object, or get the type from an existing object and invoke its methods or access its fields and properties.


1 Answers

1 million a day is not a lot; I'd just use Activator.CreateInstance (a quick test using Activator.CreatInstance(Type) shows that on my lowly laptop it can create 1M objects from aType in ~2s).

Thoughts on creating objects quickly:

  • use generics and the : new() constraint (zero effort)
  • use DynamicMethod and write the IL (not hard)

An implementation of the new approach (without needing the : new() constraint externally) is shown here: ObjectFactory.cs.

For an IL example, see dapper-dot-net and il.Emit(OpCodes.Newobj, ...)

like image 88
Marc Gravell Avatar answered Oct 09 '22 18:10

Marc Gravell