下载app免费领取会员
C# 创建对象可以直接用new,也可以用反射,下面测试一下反射创建的性能如何,
这里可以比较一下,构造方法带参数和不带参数的区别。
先创建一个测试类,分为构造函数带参数和不带参数,两种情况来测试
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;
//}
}
要测试的方法有
new
Assembly.CreateInstance
Activator.CreateInstance
ConstructorInfo.Invoke
下面是测试代码
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();
}
}
发现使用Assembly.CreateInstance是最慢的,使用new 是最快的
当构造函数带参数的时候,ConstructorInfo.Invoke是第二快的
当构造函数不带参数的时候Activator.CreateInstance是第二快的,
查看Assembly.CreateInstance的源码,发现他在内部是用Activator.CreateInstance创建的,但是多了一个寻找Type的过程,
似乎寻找Type是一件很耗时间的过程
本文版权归腿腿教学网及原创作者所有,未经授权,谢绝转载。