Development With A Dot

Blog on development in general, and specifically on .NET

Sponsors

News

My Friends

My Links

Permanent Posts

Portuguese Communities

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

Comments

SamZ said:

Which way do You prefer?

# February 8, 2010 6:51 AM

Ricardo Peres said:

SamZ:

Why don't you give it a try? :-)

Increase the number of created objects and see the results.

RP

# February 8, 2010 9:02 AM

zoldello said:

How many ways do you need to skin a cat? Having multiple ways of creating a class reminds me of that ado-database issue- where you had a thousand ways of doing one thing without adding considering value.

# February 8, 2010 11:07 AM

Ricardo Peres said:

zoldello:

Check the numbers and see for yourself!

# February 8, 2010 11:31 AM

koolraagaa said:

The Code does not build.. Gives a Message

1. Error 1 A local variable named 'creator' is already defined in this scope 46 26 ConsoleApplication1

# February 8, 2010 7:31 PM

Ricardo Peres said:

koolraagaa:

That was pretty easy to solve: just remove the second line "Func<Object> creator = ...". I updated the post.

# February 9, 2010 4:57 AM

xiety said:

Runtime error: "Method '' does not have a method body."

Line "Func<Object> creator" must come after two "il.Emit" lines.

# February 12, 2010 2:54 AM

Dirk said:

Pretty weird. I tried 1, 10, 100 en 1000 iterations.

The second option only was fastest at 10 iterations at my PC.

The third option clearly is the option when you need a lot of instances.

Personally I prefer the first option.

# March 19, 2010 5:53 AM

Ricardo Peres said:

Dirk:

Yep, I agree. Just don't forget to cache the ConstructorInfo object.

# March 19, 2010 7:24 AM