Skip to content

Instantly share code, notes, and snippets.

@hypeartist
Created July 16, 2022 19:19
Show Gist options
  • Save hypeartist/acba779134aec86bca0cc16a5a9536ab to your computer and use it in GitHub Desktop.
Save hypeartist/acba779134aec86bca0cc16a5a9536ab to your computer and use it in GitHub Desktop.
Type instantiation (default .ctor)
object obj;
var r = 0;
const int cnt = 1000000;
var constructorInfo = typeof(Class).GetConstructor(Array.Empty<Type>())!;
var hCtorDefault = constructorInfo.MethodHandle;
RuntimeHelpers.PrepareMethod(RuntimeMethodHandle.FromIntPtr(hCtorDefault.Value));
var pCtor = (delegate*<object, void>)hCtorDefault.GetFunctionPointer();
var t1 = Stopwatch.GetTimestamp();
for (int i = 0; i < cnt; i++)
{
obj = RuntimeHelpers.GetUninitializedObject(typeof(Class));
pCtor(obj);
var inst = Unsafe.As<object, Class>(ref obj);
r += inst._f;
}
var t2 = Stopwatch.GetTimestamp();
Console.WriteLine($"RuntimeHelpers.GetUninitializedObject + .ctor invocation via function pointer:\t{TimeSpan.FromTicks(t2 - t1).Milliseconds} ms");
t1 = Stopwatch.GetTimestamp();
for (int i = 0; i < cnt; i++)
{
obj = constructorInfo.Invoke(Array.Empty<object?>());
var inst = Unsafe.As<object, Class>(ref obj);
r += inst._f;
}
t2 = Stopwatch.GetTimestamp();
Console.WriteLine($"ConstructorInfo.Invoke:\t{TimeSpan.FromTicks(t2 - t1).Milliseconds} ms");
t1 = Stopwatch.GetTimestamp();
for (int i = 0; i < cnt; i++)
{
var c = Activator.CreateInstance(typeof(Class));
var inst = Unsafe.As<object, Class>(ref c!);
r += inst._f;
}
t2 = Stopwatch.GetTimestamp();
Console.WriteLine($"Activator.CreateInstance:\t\t\t\t\t\t\t{TimeSpan.FromTicks(t2 - t1).Milliseconds} ms");
t1 = Stopwatch.GetTimestamp();
for (int i = 0; i < cnt; i++)
{
var inst = new Class();
r += inst._f;
}
t2 = Stopwatch.GetTimestamp();
Console.WriteLine($"Implicit call via 'new':\t\t\t\t\t\t\t{TimeSpan.FromTicks(t2 - t1).Milliseconds} ms");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment