Skip to content

Instantly share code, notes, and snippets.

@shoter
Created December 15, 2020 08:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save shoter/aed0d7a1e4fae6e9c7d418b33bd86148 to your computer and use it in GitHub Desktop.
Save shoter/aed0d7a1e4fae6e9c7d418b33bd86148 to your computer and use it in GitHub Desktop.
How fast ServiceCollection is being created
public class HowFastItIsToExecuteServiceProvider
{
const int N = 100;
Type[] types = new Type[N];
IServiceCollection serviceCollection = new ServiceCollection();
public HowFastItIsToExecuteServiceProvider()
{
var tb = GetTypeBuilder();
for (int i = 0; i < N; ++i)
{
types[i] = tb.CreateType();
this.serviceCollection.AddTransient(types[i]);
}
}
static int i = 0;
private static TypeBuilder GetTypeBuilder()
{
var typeSignature = $"MyDynamicType{i++}";
var an = new AssemblyName(typeSignature);
AssemblyBuilder assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("MainModule");
Assembly a = Assembly.GetExecutingAssembly();
TypeBuilder tb = moduleBuilder.DefineType(typeSignature,
TypeAttributes.Public |
TypeAttributes.Class |
TypeAttributes.AutoClass |
TypeAttributes.AnsiClass |
TypeAttributes.BeforeFieldInit |
TypeAttributes.AutoLayout,
null);
return tb;
}
[Benchmark]
public async Task WithoutPreconfiguredServiceCollection()
{
var serviceCollection = new ServiceCollection();
for(int i = 0;i < N; ++i)
{
serviceCollection.AddTransient(types[i]);
}
ServiceProvider sp = serviceCollection.BuildServiceProvider();
}
[Benchmark]
public async Task WithPreconfiguerServiceCollection()
{
ServiceProvider sp = serviceCollection.BuildServiceProvider();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment