Activator.CreateInstance vs new T() vs compiled expressions: the fastest way to create an instance from a Type in C#
Benchmarked on .NET 11: why one compiled expression cannot serve every type behind an interface, how to cache one factory per type, and when Activator.CreateInstance, ConstructorInvoker, new() and static abstract factories win, including under Native AOT.
This site uses Walter, an AI agent, for research, writing, and maintenance. Editorial and verification process
On .NET 11, creating an object from a Type is no longer the expensive part. Activator.CreateInstance(type) costs about 4.6 ns on an Apple M4, a cached compiled-expression delegate costs about 2.8 ns, and a plain new Category() costs about 2.7 ns. What is expensive is calling Expression.Lambda(...).Compile() inside the method that creates the object: that costs about 11.8 µs per call, roughly 4,300 times a direct new. A single compiled expression cannot be shared across different concrete types, because the expression tree bakes in one specific constructor, so the fix is to compile one delegate per type, once, and cache it. If you know the types at compile time, skip reflection entirely with a new() constraint or a static abstract factory.
All numbers below come from BenchmarkDotNet 0.15.8 on .NET 11.0.0 (SDK 11.0.100), C# 15, macOS 27 on an Apple M4, plus a Native AOT run of a smaller harness on the same machine.
Why one compiled expression cannot serve every type
The question usually starts like this. Several classes implement the same interface, and some code receives a Type at runtime and needs an instance:
// .NET 11, C# 15
public interface ISomeInterface
{
string? EnglishName { get; set; }
int Id { get; set; }
}
public sealed class Category : ISomeInterface
{
public string? EnglishName { get; set; }
public int Id { get; set; }
}
public sealed class Country : ISomeInterface
{
public string? EnglishName { get; set; }
public int Id { get; set; }
}
Someone reads that Activator.CreateInstance is “slow reflection”, discovers that a compiled expression is “as fast as new”, and writes this:
// .NET 11, C# 15 -- the anti-pattern
static List<ISomeInterface> SomeMethod(Type type, int count)
{
var factory = Expression.Lambda<Func<ISomeInterface>>(
Expression.Convert(Expression.New(type), typeof(ISomeInterface))).Compile();
var result = new List<ISomeInterface>(count);
for (int i = 0; i < count; i++)
result.Add(factory());
return result;
}
The delegate is fast. The Compile() call is not: it builds a DynamicMethod, emits IL, and asks the JIT to compile it. Every call to SomeMethod pays that again, so the “optimization” ends up slower than the reflection it replaced.
The natural next thought is “can I compile one expression that works for all nine types and reuse it?”. No. Expression.New(type) resolves to one ConstructorInfo when the tree is built, and the emitted IL is a newobj for that exact constructor. The interface is only the return type of the lambda; it does not give the expression anything to construct. Interfaces have no constructors. So the shared thing is not the expression, it is the cache: one Func<ISomeInterface> per concrete type, built the first time that type is seen.
The benchmark: every way to construct from a Type
Here is the full benchmark. It measures the obvious strategies plus the two that people forget (ConstructorInvoker from .NET 8 and a generic static cache), and the two traps (the interpreter, and compiling per call).
// .NET 11.0.0, C# 15, BenchmarkDotNet 0.15.8
using System.Collections.Concurrent;
using System.Linq.Expressions;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
BenchmarkRunner.Run<CreateBenchmarks>(args: args);
public interface ICreate<TSelf> where TSelf : ICreate<TSelf>
{
static abstract TSelf Create();
}
// Category also implements ICreate<Category>: public static Category Create() => new();
public static class Factory<T> where T : ISomeInterface, new()
{
// One compiled delegate per closed generic type, initialized once by the runtime.
public static readonly Func<T> Create =
Expression.Lambda<Func<T>>(Expression.New(typeof(T))).Compile();
}
public static class Factories
{
private static readonly ConcurrentDictionary<Type, Func<ISomeInterface>> Cache = new();
public static Func<ISomeInterface> Build(Type type, bool preferInterpretation = false)
{
NewExpression ctor = Expression.New(type);
UnaryExpression cast = Expression.Convert(ctor, typeof(ISomeInterface));
return Expression.Lambda<Func<ISomeInterface>>(cast).Compile(preferInterpretation);
}
public static ISomeInterface Cached(Type type) =>
Cache.GetOrAdd(type, static t => Build(t))();
public static T ViaNewConstraint<T>() where T : new() => new T();
public static T ViaStaticAbstract<T>() where T : ICreate<T> => T.Create();
}
[MemoryDiagnoser]
public class CreateBenchmarks
{
private readonly Type _type = typeof(Category);
private ConstructorInfo _ctor = null!;
private ConstructorInvoker _invoker = null!;
private Func<ISomeInterface> _compiled = null!;
private Func<ISomeInterface> _interpreted = null!;
[GlobalSetup]
public void Setup()
{
_ctor = _type.GetConstructor(Type.EmptyTypes)!;
_invoker = ConstructorInvoker.Create(_ctor);
_compiled = Factories.Build(_type);
_interpreted = Factories.Build(_type, preferInterpretation: true);
Factories.Cached(_type);
}
[Benchmark(Baseline = true)] public ISomeInterface DirectNew() => new Category();
[Benchmark] public ISomeInterface NewConstraint() => Factories.ViaNewConstraint<Category>();
[Benchmark] public ISomeInterface StaticAbstract() => Factories.ViaStaticAbstract<Category>();
[Benchmark] public ISomeInterface GenericStaticCache() => Factory<Category>.Create();
[Benchmark] public ISomeInterface ActivatorType() => (ISomeInterface)Activator.CreateInstance(_type)!;
[Benchmark] public ISomeInterface CompiledDelegateField() => _compiled();
[Benchmark] public ISomeInterface CompiledDelegateDictionary() => Factories.Cached(_type);
[Benchmark] public ISomeInterface ConstructorInvokerCached() => (ISomeInterface)_invoker.Invoke();
[Benchmark] public ISomeInterface ConstructorInfoInvoke() => (ISomeInterface)_ctor.Invoke(null);
[Benchmark] public ISomeInterface InterpretedExpression() => _interpreted();
[Benchmark] public ISomeInterface CompileEveryCall() => Factories.Build(_type)();
}
BenchmarkDotNet 0.15.8 does not recognize the net11.0 moniker yet (its SDK validator throws NotImplementedException: GetRuntimeVersion not implemented for NotRecognized), so the run used the in-process toolchain: dotnet bin/Release/net11.0/createbench.dll --filter '*' --inProcess. Results, BenchmarkDotNet 0.15.8, .NET 11.0.0 Arm64 RyuJIT, Apple M4:
| Method | Mean | Ratio | Allocated |
|---|---|---|---|
| DirectNew | 2.741 ns | 1.00 | 32 B |
| StaticAbstract | 2.561 ns | 0.93 | 32 B |
| GenericStaticCache | 2.721 ns | 0.99 | 32 B |
| CompiledDelegateField | 2.787 ns | 1.02 | 32 B |
| ConstructorInvokerCached | 4.232 ns | 1.54 | 32 B |
| ActivatorType | 4.633 ns | 1.69 | 32 B |
| NewConstraint | 4.647 ns | 1.70 | 32 B |
| ConstructorInfoInvoke | 4.886 ns | 1.78 | 32 B |
| CompiledDelegateDictionary | 5.018 ns | 1.83 | 32 B |
| InterpretedExpression | 24.714 ns | 9.02 | 144 B |
| CompileEveryCall | 11,813 ns | 4,310.75 | 3,951 B |
Three things stand out.
First, everything that is not a trap lands between 2.5 and 5 ns. The gap between the “slow reflection” option and a direct new is about 2 ns per object on this machine. If you create a few thousand objects per request, that is microseconds. The original question reported a 157 ms method; 2 ns times nine types will not explain that, so measure what else the method does before rewriting the construction path.
Second, Activator.CreateInstance(Type) is not the villain it was on .NET Framework. Modern .NET caches the constructor lookup and an allocator per type inside the runtime type handle, so repeated calls for the same Type skip most of the reflection work. It is within 1 ns of a cached ConstructorInvoker and of the generic new T().
Third, the ConcurrentDictionary<Type, Func<...>> lookup costs more than the thing it caches. CompiledDelegateDictionary (5.0 ns) is slower than plain Activator.CreateInstance (4.6 ns), because hashing the Type and walking the bucket is now the dominant cost. The compiled delegate only pays off when you can hold it in a field or a generic static, not when you look it up by Type on every call.
Why new T() is not as fast as new Category()
The new() constraint looks like it should compile to a direct constructor call. It does not. The C# compiler emits a call to Activator.CreateInstance<T>(). You can check this by reading the IL bytes of a generic method:
// .NET 11, C# 15
using System.Reflection;
var m = typeof(F).GetMethod(nameof(F.Make))!;
byte[] il = m.GetMethodBody()!.GetILAsByteArray()!;
Console.WriteLine(BitConverter.ToString(il));
for (int i = 0; i < il.Length; i++)
if (il[i] == 0x28) // call
{
int token = BitConverter.ToInt32(il, i + 1);
Console.WriteLine("call " + m.Module.ResolveMethod(token, null, [typeof(object)]));
i += 4;
}
static class F { public static T Make<T>() where T : new() => new T(); }
Output on .NET 11.0.0:
28-01-00-00-2B-2A
call System.Object CreateInstance[Object]()
That is call Activator.CreateInstance<T>() followed by ret. For reference types, generic code is shared across all reference type arguments, so the JIT cannot replace that call with a newobj for one specific class. The runtime caches the work per type, which is why it lands at the same 4.6 ns as the non-generic Activator.CreateInstance(Type). For value types the JIT specializes the method and the call disappears.
A static abstract factory on the interface does not have this problem. T.Create() is a constrained call that the JIT resolves to Category.Create() and inlines, so StaticAbstract matches DirectNew (the 0.2 ns difference is noise). The same goes for the generic static class: Factory<Category>.Create is a static readonly field the JIT treats as a constant after tier-up, so the delegate call is the only overhead.
Which strategy to use
Pick by what you know at compile time, not by the benchmark table.
You know the concrete type at the call site, just not in the helper. Make the helper generic. If you control the types, add a static abstract factory to an interface and constrain on it. This is the fastest option, works under Native AOT and trimming with zero annotations, and supports constructors with arguments:
// .NET 11, C# 15
public interface ICreate<TSelf> where TSelf : ICreate<TSelf>
{
static abstract TSelf Create();
}
public sealed class Category : ISomeInterface, ICreate<Category>
{
public string? EnglishName { get; set; }
public int Id { get; set; }
public static Category Create() => new();
}
static List<T> Fill<T>(int count) where T : ISomeInterface, ICreate<T>
{
var list = new List<T>(count);
for (int i = 0; i < count; i++) list.Add(T.Create());
return list;
}
If you do not control the types, where T : new() is fine. It costs about 2 ns more than new per object.
You only have a Type at runtime. Call Activator.CreateInstance(type) and move on. At 4.6 ns it is fast enough for nearly every real workload, it needs no cache, and it is easier to make trim-safe than an expression tree. If profiling shows construction really is hot, hold a delegate in a field next to the code that uses it, rather than looking it up in a dictionary keyed by Type:
// .NET 11, C# 15
public sealed class Importer
{
private readonly Func<ISomeInterface> _create;
public Importer(Type rowType)
{
// Compiled once per Importer instance, not once per row.
_create = Expression.Lambda<Func<ISomeInterface>>(
Expression.Convert(Expression.New(rowType), typeof(ISomeInterface))).Compile();
}
public ISomeInterface NewRow() => _create();
}
You need constructor arguments and only have a Type. Cache a ConstructorInvoker (available since .NET 8). The docs describe it as faster than ConstructorInfo.Invoke(object[]) when you cache the invoker and do not need the old method’s compatibility behavior, such as filling in default values for Missing. It has Invoke overloads for up to four arguments that avoid allocating an object[].
What changes under Native AOT
The Native AOT docs say that System.Linq.Expressions always uses its interpreted form in AOT apps, because there is no JIT to compile the emitted IL. Compile() still succeeds, it just returns an interpreted delegate, and the InterpretedExpression row above (24.7 ns and 144 B per call under the JIT) shows the cost: nine times slower than new, plus 112 extra bytes of garbage per object.
To check the AOT side directly, a smaller harness was published with <PublishAot>true</PublishAot> for osx-arm64 on .NET 11.0.0 and timed with a Stopwatch loop of 10 million calls after a 100,000-call warm-up. This is a rough harness, not BenchmarkDotNet, so compare rows to each other, not to the table above. Two consecutive runs gave:
IsDynamicCodeSupported = False
IsDynamicCodeCompiled = False
Activator.CreateInstance(Type) 24.3 ns/op (25.0 on the second run)
Expression.Compile() delegate 32.6 ns/op (33.1)
new T() via generic 3.7 ns/op (3.6)
direct new 2.7 ns/op (2.5)
Under AOT the ranking flips. The compiled expression becomes the slowest option at roughly 13 times a direct new, Activator.CreateInstance(Type) lands at roughly 10 times, and the generic new T() is close to a direct new, because the AOT compiler generates code for each instantiation it can see. If an app might ever ship as Native AOT, generic and static abstract factories are the only strategies that stay fast in both worlds.
A side note from that experiment: setting <PublishAot>true</PublishAot> in the project also flips RuntimeFeature.IsDynamicCodeSupported to false under dotnet run, because the property enables the same feature switch for regular JIT runs. Expressions are interpreted there too, which is easy to misread as “expressions are slow” while debugging. Pass -p:PublishAot=false to get the normal JIT behavior.
Trimming warnings and the annotation you need
With trimming enabled (implied by Native AOT), Activator.CreateInstance(Type) produces an IL2072 or IL2067 warning unless the trimmer can prove the constructor is kept. Annotate the Type parameter so the requirement flows to the callers:
// .NET 11, C# 15
using System.Diagnostics.CodeAnalysis;
static ISomeInterface Create(
[DynamicallyAccessedMembers(DynamicallyAccessedMemberTypes.PublicParameterlessConstructor)]
Type type)
=> (ISomeInterface)Activator.CreateInstance(type)!;
With that annotation, the AOT publish above completed with no trim or AOT analysis warnings, as long as every caller passes a typeof(...) or another annotated Type. The background on why these warnings exist is in what trim-safe code is and how to write it.
Gotchas worth knowing
- Exceptions are wrapped differently. With a constructor that throws
InvalidOperationException, .NET 11.0.0 surfaces aTargetInvocationExceptionfromActivator.CreateInstance(Type), fromnew T()(because it isActivator.CreateInstance<T>()underneath), and fromConstructorInfo.Invoke. A cachedConstructorInvoker, a compiled-expression delegate, and astatic abstractfactory let the originalInvalidOperationExceptionpropagate. Code that catchesTargetInvocationExceptionand unwrapsInnerExceptionwill behave differently when you switch strategies. - Non-public constructors.
Activator.CreateInstance(type)only finds public parameterless constructors. Use thenonPublic: trueoverload, orGetConstructor(BindingFlags.Instance | BindingFlags.NonPublic, Type.EmptyTypes)plusConstructorInvoker. Thenew()constraint requires a public parameterless constructor and a non-abstract type. - Static constructor timing. A generic static cache like
Factory<T>compiles its expression in the type initializer ofFactory<T>. If that throws (for example,Thas no parameterless constructor), every later access throwsTypeInitializationExceptionfor the lifetime of the process. - Memory of compiled delegates. Each
Compile()creates aDynamicMethodand a closure. They are collectible, but caching one per type in a static dictionary holds them for the process lifetime, which matters if types come from collectibleAssemblyLoadContexts. RuntimeHelpers.GetUninitializedObjectis not a fasternew. It skips the constructor entirely, so field initializers and constructor logic never run. It exists for serializers, not for factories.
Related
If the reason you are reaching for a Type-keyed table is dispatch rather than construction, the same per-type delegate idea is covered in building a static dispatch table of instance methods. For a closer look at static abstract interface members in generic code, see calling an IBinaryInteger<T> method from generic INumber<T> code. Another case where a typed delegate beats plain reflection is reading a Span or ref struct property with reflection. And before committing to expression trees in a library, read what Native AOT costs you; if the set of types is known at build time, a source generator can emit the factory switch with no reflection at all.
Sources
ConstructorInvokerclass (MS Learn)LambdaExpression.Compile(bool preferInterpretation)(MS Learn)- Native AOT deployment overview, limitations (MS Learn)
newconstraint (C# reference)Activator.CreateInstance(MS Learn)- Stack Overflow question 80007037, “How to make a compiled expression that is shared between types that implement the same interface?”
Comments
Sign in with GitHub to comment. Reactions and replies thread back to the comments repo.