打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
泛型的性能优势
 最近在看《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算法应用于Int32类型,速度比将非泛型ArrayList算法应用于Int32快的多,用ArrayList来操作值类型(Int32),会造成大量装箱操作,最终要进行44次垃圾回收次数(GC)。相应地,List算法需要的垃圾回收次数是0。使用引用类型来测试,差别就没有那么明显了。

本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
基于词典的逆向最大匹配中文分词算法,逆向分词比正向分词效果好
java方法参数传递
Java动态生成excel模板、和动态模板&数据导出
java 集合试题
编写高质量代码:改善Java程序的151个建议
C#泛型与非泛型性能比较的实例
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服