Class 创建性能测试

using System;
using System.Collections.Generic;
using System.Diagnostics;

namespace ConsoleApplication5_Inject
{
class Entity { }

class Program
{
staticvoid Main(string[] args)
{
#region Run1
Stopwatch sw
=new Stopwatch();
sw.Start();
for (int i =0; i <100000; i++)
{
Run1();
}
sw.Stop();
Console.WriteLine(sw.Elapsed.Milliseconds);
#endregion

#region Run2
sw
=new Stopwatch();
sw.Start();
for (int i =0; i <100000; i++)
{
Run2();
}
sw.Stop();
Console.WriteLine(sw.Elapsed.Milliseconds);
#endregion

#region Run3
sw
=new Stopwatch();
sw.Start();
for (int i =0; i <100000; i++)
{
Run3();
}
sw.Stop();
Console.WriteLine(sw.Elapsed.Milliseconds);
#endregion

#region Run4
sw
=new Stopwatch();
sw.Start();
for (int i =0; i <100000; i++)
{
Run4
<Entity>();
}
sw.Stop();
Console.WriteLine(sw.Elapsed.Milliseconds);
#endregion

Console.ReadKey();
}

staticvoid Run1()
{
new Entity();
}

staticvoid Run2()
{
Activator.CreateInstance(
typeof(Entity));
}

staticvoid Run3()
{
Activator.CreateInstance
<Entity>();
}

staticvoid Run4<T>() where T : new()
{
new T();
}
}
}

跑10万次 结果:

1. 3ms

2. 220ms

3. 117ms

4. 121ms

posted @ 2011-05-24 14:12  一浩瀚星空一  阅读(175)  评论(0编辑  收藏  举报