Have ConstructorInfo
use Activator.CreateInstance()
instead of emit for default constructors
#78917
Labels
area-System.Reflection
Cost:M
Work that requires one engineer up to 2 weeks
tenet-performance
Performance related issue
Milestone
Activator.CreateInstance()
was optimized in v6 and made super fast when invoking the default constructor. As shown in the benchmarks below, currently calling a zero-parameter constructor throughActivator.CreateInstance(...)
is ~1.7x faster thanConstructorInfo
. Note that before the 7.0 feature to use IL emit,Activator.CreateInstance(...)
used to be ~6x faster thanConstructorInfo
.Although
Activator
is faster thanConstructorInfo
that only applies for cases when there is a default constructor. When there are constructor parameters, callingConstructorInfo
is up to 2x faster.Due to the varying performance of these two APIs, reflection users that need to invoke constructors and want the maximum performance currently need to call
ConstructorInfo
when there are parameters andActivator
when there are no parameters. This issue should make this choice go away by makingConstructorInfo
the preferred API going forward for almost all cases by havingConstructorInfo
callActivator
for default constructors. This also avoids generating IL for these cases which can help with start-up and reduce global memory usage.Using
ConstructorInfo
instead ofActivator
also has the advantage of forcing the caller select the appropriate constructor ahead of time, instead of auto-selecting each time the method is called by inspecting the parameters. If the caller does not know what constructor to call, then continuing to useActivator
is fine.We also need to look at normalizing the exception handling between these two APIs so they have the same Exception semantics for
OutOfMemoryException
.Also see #36194 for ideas on exposing "Factory" overloads that will not throw `TargetInvocationException".
The text was updated successfully, but these errors were encountered: