下載app免費(fèi)領(lǐng)取會(huì)員
C# 創(chuàng)建對(duì)象可以直接用new,也可以用反射,下面測(cè)試一下反射創(chuàng)建的性能如何,
這里可以比較一下,構(gòu)造方法帶參數(shù)和不帶參數(shù)的區(qū)別。
先創(chuàng)建一個(gè)測(cè)試類,分為構(gòu)造函數(shù)帶參數(shù)和不帶參數(shù),兩種情況來(lái)測(cè)試
public class Test
{
public string Name { get; set; }
public string Id { get; set; }
public Test(string name, string id)
{
Name = name;
Id = id;
}
//public Test()
//{
// //Name = name;
// //Id = id;
//}
}
要測(cè)試的方法有
new
Assembly.CreateInstance
Activator.CreateInstance
ConstructorInfo.Invoke
下面是測(cè)試代碼
class Program
{
static void Main(string[] args)
{
int m = 1000000;
int i = 0;
string typeName = typeof(Test).FullName;
Assembly ab = typeof(Test).Assembly;
Type type = typeof(Test);
ConstructorInfo cinfo = type.GetConstructors().First();
object[] ps = new object[] { "name", "id" };
Stopwatch stopWatch = new Stopwatch();
Console.WriteLine("---------------------------------------------");
Console.WriteLine("new");
stopWatch.Start();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
while(i<m)
{
Test t = new Test("name","id");
i++;
}
Console.WriteLine(stopWatch.ElapsedMilliseconds);
stopWatch.Stop();
stopWatch.Reset();
i = 0;
Console.WriteLine("---------------------------------------------");
Console.WriteLine("assembly");
stopWatch.Start();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
while (i < m)
{
Test t = ab.CreateInstance(typeName, false, BindingFlags.Public| BindingFlags.CreateInstance| BindingFlags.Instance, null, ps, null, null) as Test;
//Test t = ab.CreateInstance(typeName) as Test;
i++;
}
Console.WriteLine(stopWatch.ElapsedMilliseconds);
stopWatch.Stop();
stopWatch.Reset();
i = 0;
Console.WriteLine("---------------------------------------------");
Console.WriteLine("Activetor");
stopWatch.Start();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
while (i < m)
{
Test t = Activator.CreateInstance(type,ps) as Test;
i++;
}
Console.WriteLine(stopWatch.ElapsedMilliseconds);
stopWatch.Stop();
stopWatch.Reset();
i = 0;
Console.WriteLine("---------------------------------------------");
Console.WriteLine("ConstructorInfo");
stopWatch.Start();
Console.WriteLine(stopWatch.ElapsedMilliseconds);
while (i < m)
{
Test t = cinfo.Invoke(ps) as Test;
//Test t = cinfo.Invoke(null) as Test;
i++;
}
Console.WriteLine(stopWatch.ElapsedMilliseconds);
Console.ReadLine();
}
}
發(fā)現(xiàn)使用Assembly.CreateInstance是最慢的,使用new 是最快的
當(dāng)構(gòu)造函數(shù)帶參數(shù)的時(shí)候,ConstructorInfo.Invoke是第二快的
當(dāng)構(gòu)造函數(shù)不帶參數(shù)的時(shí)候Activator.CreateInstance是第二快的,
查看Assembly.CreateInstance的源碼,發(fā)現(xiàn)他在內(nèi)部是用Activator.CreateInstance創(chuàng)建的,但是多了一個(gè)尋找Type的過(guò)程,
似乎尋找Type是一件很耗時(shí)間的過(guò)程
本文版權(quán)歸腿腿教學(xué)網(wǎng)及原創(chuàng)作者所有,未經(jīng)授權(quán),謝絕轉(zhuǎn)載。
上一篇:二次開發(fā)教程:C# 初探UI Automation
下一篇:關(guān)于revit中2D軸網(wǎng)與3D的區(qū)別
推薦專題