Three Ways To Create An Object

Enjoy!

Type type = typeof(StringBuilder);	//can be any type
ConstructorInfo ci = type.GetConstructor(new Type [ 0 ]);
Stopwatch watch = new Stopwatch();

watch.Start();
			
for (Int32 i = 0; i < 100; ++i)
{
	StringBuilder obj = Activator.CreateInstance(type) as StringBuilder;
}

Int64 time1 = watch.ElapsedTicks;

watch.Reset();

watch.Start();

for (Int32 i = 0; i < 100; ++i)
{
	StringBuilder obj = ci.Invoke(null) as StringBuilder;
}

Int64 time2 = watch.ElapsedTicks;

DynamicMethod m = new DynamicMethod(String.Empty, typeof(Object), null, type, true);
			
ILGenerator il = m.GetILGenerator();
il.Emit(OpCodes.Newobj, ci);
il.Emit(OpCodes.Ret);
Func<Object> creator = m.CreateDelegate(typeof(Func<Object>)) as Func<Object>;

watch.Reset();

watch.Start();

for (Int32 i = 0; i < 100; ++i)
{
	StringBuilder obj = creator() as StringBuilder;
}

Int64 time3 = watch.ElapsedTicks;

Bookmark and Share

                             

9 Comments

Add a Comment

As it will appear on the website

Not displayed

Your website