分享

泛型的性能优势

 昵称10504424 2013-07-16
 最近在看《CLR via C#》,有关泛型的优势,感觉说的挺不错的特记录一下,以供以后查看。

    泛型为开发人员提供的优势:

  1. 源代码保护
  2. 类型安全
  3. 更清晰的代码
  4. 更佳的性能

为了理解泛型的优势,写了一个程序来比较泛型List算法和FCL的非泛型ArrayList算法的性能。同时使用值类型和引用类型的对象来测试这两个算法的性能:

static void Main(string[] args)
{
ValueTypePerfTest();
ReferenceTypePerfTest();
Console.ReadLine();
}
public static void ValueTypePerfTest()
{
const Int32 count = 10000000;
using (new OperationTimer("List<Int32>"))
{
List<Int32> l = new List<Int32>(count);
for (Int32 i = 0; i < count; i++)
{
l.Add(i);
Int32 x = l[i];
}
l = null;
}
using (new OperationTimer("ArrayList of Int32"))
{
ArrayList a = new ArrayList();
for (Int32 i = 0; i < count; i++)
{
a.Add(i);
Int32 x = (Int32)a[i];
}
a = null;
}
}
public static void ReferenceTypePerfTest()
{
const Int32 count = 10000000;
using (new OperationTimer("List<string>"))
{
List<string> l = new List<string>();
for (Int32 i = 0; i < count; i++)
{
l.Add("X");
string x = l[i];
}
l = null;
}
using (new OperationTimer("ArrayList of string"))
{
ArrayList a = new ArrayList();
for (Int32 i = 0; i < count; i++)
{
a.Add("X");
string x = (String)a[i];
}
a = null;
}
Console.ReadLine();
}
}
internal sealed class OperationTimer : IDisposable
{
private Int64 m_startTime;
private string m_text;
private Int32 m_collectionount;
public OperationTimer(string text)
{
PrepareForOperation();
m_text = text;
m_collectionount = GC.CollectionCount(0);
m_startTime = Stopwatch.GetTimestamp();
}
public void Dispose()
{
Console.WriteLine("{0,6:###.00} seconds (GCs={1,3})  {2}",
(Stopwatch.GetTimestamp()-m_startTime)/(Double)Stopwatch.Frequency,
GC.CollectionCount(0)-m_collectionount,m_text);
}
private static void PrepareForOperation()
{
GC.Collect();
GC.WaitForPendingFinalizers();
GC.Collect();
}


输出结果如下:

list

    这个输出结果证明:将泛型list算法应用于Int32类型,速度比将非泛型ArrayList算法应用于Int32快的多,用ArrayList来操作值类型(Int32),会造成大量装箱操作,最终要进行44次垃圾回收次数(GC)。相应地,List算法需要的垃圾回收次数是0。使用引用类型来测试,差别就没有那么明显了。

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约