Question

Is the execution time (run-time) performance of code in a class that is loaded via reflection identical to the same code when the class is created using the new keyword?

I say yes. But I was discussing this with a colleague who believes that the reflection oriented code is always slower.

My view is that regardless of how the class was originally loaded/created, the performance will be identical because the JIT compiler does not care how a class was loaded.

Am I correct? Either way, I'd appreciate any references that can help clarify this.

(NB: I'm not talking about the performance of creating a class using reflection versus the new keyword. I'm referring to the actual code in methods of the class after it has been created.)

Was it helpful?

Solution

It depends on how you execute it ;-p

Once you're inside the methods on the loaded type, yes: regular GIT etc applies normally (note that security checks may make things a little slower if it is partially trusted, but not much).

But first you need to invoke some code on the dynamic object:

  • If you can cast the object to an interface or base-class that is known statically, then it will be identical.
  • If this isn't possible, but you can bind specific operations to known delegates (for example Func<string,int>, via Delegate.CreateDelegate), then it will be almost as fast, but less convenient.
  • If you do everything via DynamicInvoke(), it will be pretty treacle-like.
  • In 4.0, dynamic may offer a halfway house, in that it offers duck-typing with optimised caching per type.

So: how are you accessing it?

OTHER TIPS

Yes, once loaded the performance is the same.

The performance penalty of reflection is bound to the reading of the metadata from the assembly but the execution time will be exactly the same. That is, once the instance has been created and you have a reference to it, it will behave as any other class you have (including JIT compiling and everything).

It depends on how you use reflection. It's always slower, but you can make the time difference really small if you use IL emit to create a factory method in runtime. If you use the simple Activator.CreateInstance, it will be so much slower.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top