Skip to content

Instantly share code, notes, and snippets.

@KallDrexx
Last active May 4, 2021 18:43
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 KallDrexx/d08a60f2d807673af1d9e90e07d61aeb to your computer and use it in GitHub Desktop.
Save KallDrexx/d08a60f2d807673af1d9e90e07d61aeb to your computer and use it in GitHub Desktop.
C# Create Instance Performance
| Method | Mean | Error | StdDev | Median |
|----------------------------------------------------------- |-----------:|-----------:|-----------:|-----------:|
| Direct | 5.481 ns | 0.2822 ns | 0.8188 ns | 5.271 ns |
| GenericActivator | 43.534 ns | 0.8644 ns | 1.3201 ns | 43.480 ns |
| CastedActivator | 46.221 ns | 0.9988 ns | 2.7511 ns | 45.433 ns |
| FromReflectedConstructor | 100.869 ns | 2.0531 ns | 2.8103 ns | 100.478 ns |
| CastedActivatorWithParams | 779.257 ns | 15.5720 ns | 23.3074 ns | 783.431 ns |
| FromReflectedConstructorWithParams | 177.763 ns | 3.6355 ns | 6.8283 ns | 176.539 ns |
| FromReflectedConstructorWithParamsWithoutCachedConstructor | 499.329 ns | 10.0236 ns | 15.3071 ns | 495.609 ns |
using System;
using System.Reflection;
using BenchmarkDotNet.Attributes;
using BenchmarkDotNet.Running;
namespace Benchmarking
{
public class Program
{
public Program() { }
public Program(int test) { }
static void Main(string[] args)
{
BenchmarkRunner.Run<Benchmarking>();
}
}
public class Benchmarking
{
private readonly ConstructorInfo _constructorInfo = typeof(Program).GetConstructor(Array.Empty<Type>());
private readonly ConstructorInfo _constructorWIthParamInfo = typeof(Program).GetConstructor(new[] {typeof(int)});
[Benchmark]
public Program Direct()
{
return new Program();
}
[Benchmark]
public Program GenericActivator()
{
return Activator.CreateInstance<Program>();
}
[Benchmark]
public Program CastedActivator()
{
return (Program) Activator.CreateInstance(typeof(Program));
}
[Benchmark]
public Program FromReflectedConstructor()
{
return (Program) _constructorInfo.Invoke(null);
}
[Benchmark]
public Program CastedActivatorWithParams()
{
return (Program) Activator.CreateInstance(typeof(Program), 6);
}
[Benchmark]
public Program FromReflectedConstructorWithParams()
{
return (Program) _constructorWIthParamInfo.Invoke(new object?[]{5});
}
[Benchmark]
public Program FromReflectedConstructorWithParamsWithoutCachedConstructor()
{
return (Program) typeof(Program).GetConstructor(new[] {typeof(int)}).Invoke(new object?[]{5});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment