ContructorInfo.Invoke vs. Delegate

I saw several questions here in SO about how to get a delegate to create an object instead of using ConstructorInfo.Invoke .

Here is an example: Using a delegate to invoke the constructor .

I just want to know why? If it's performance, why is the delegate faster?

Update

I understand that when you create a delegate, you get rid of validation when reusing it. This is an increase in productivity.

But does this happen when the constructor is called through the delegate? Same as doing var a = new XXX() or something else?

Do ConstructorInfo.Invoke() do the same as new XXX() ? (Do not consider validation)

When using Activator.CreateInstance() do it in much the same way as Constructor.Invoke() (except for searching / type checking).

I think my question boils down to: Is it possible to create objects in different ways (for example, different IL instructions) or all mention methods using the same instructions (s), but with different types of checks before the actual creation?

+4
source share
1 answer

A few reasons:

  • In different places you need to provide a delegate. If something requires Func<T> , you cannot just give it ConstructorInfo .
  • The safe type is safe — you can guarantee which type will be created (or at least a compatible type), and you know what arguments are needed (if any). Calling ConstructorInfo.Invoke , at run time many times when you call it, there are many errors, not just when creating a delegate.
  • This is faster because the whole check (access, arguments), etc. runs once when a delegate is created, and not every time the ConstructorInfo.Invoke method is called.
+3
source

Source: https://habr.com/ru/post/1341302/


All Articles