Created
December 15, 2020 08:25
-
-
Save shoter/aed0d7a1e4fae6e9c7d418b33bd86148 to your computer and use it in GitHub Desktop.
How fast ServiceCollection is being created
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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