zoukankan      html  css  js  c++  java
  • 高效代码指泛型代替非泛型

    用泛型代替非泛型,提高效率。

    今天测试了一下使用泛型和非泛型的效率问题,结果一目了然。

    例子代码如下:

    public class Test

    {

    static int collectionCount = 0;
    static Stopwatch watch = null;
    static int testCount = 1000000;

    public static void TestBegin()
    {
    GC.Collect();////强制对所有代码进行垃圾回收
    GC.WaitForPendingFinalizers();////挂起线程,直到处理终结器队列的线程清空改队列。
    GC.Collect();////再此回收。
    collectionCount = GC.CollectionCount(0);////返回在代码执行中垃圾回收次数
    watch = new Stopwatch();
    watch.Start();

    }

    public static void TestEnd()
    {
    watch.Stop();
    Console.WriteLine("消耗的时间:{0}",watch.ElapsedMilliseconds.ToString());
    Console.WriteLine("垃圾回收的次数:{0}",GC.CollectionCount(0)-collectionCount);
    }

    /// <summary>
    /// 测试arraylist性能
    /// </summary>
    public static void TestArrayList()
    {
    ArrayList arrayList = new ArrayList();
    int temp = 0;
    for (int i = 0; i < testCount; i++)
    {
    arrayList.Add(i);
    temp=(int)arrayList[i];
    }
    arrayList = null;
    }

    /// <summary>
    /// 测试泛型的性能
    /// </summary>
    public static void TestGenericList()
    {
    List<int> list = new List<int>();
    int temp = 0;
    for (int i = 0; i < testCount;i++ )
    {
    list.Add(i);
    temp=list[i];
    }
    list = null;
    }

    public static void main(string []args)

    {

    Console.WriteLine("开始测试性能arraylist");
    TestBegin();
    TestArrayList();
    TestEnd();

    Console.WriteLine("开始测试性能List<T>泛型:");
    TestBegin();
    TestGenericList();
    TestEnd();

    Console.ReadLine();

    }

    }

    运行结果如下:

    可以看到,泛型的效率高很多。

    没有什么优雅的代码比空代码的执行效率更高
  • 相关阅读:
    MVC框架简介
    模型-视图-控制器模式
    高德地图基本开发
    质量属性的六个常见属性场景分析
    架构漫谈读后感
    第十周
    第九周总结
    第八周总结
    springboot基于mybatis的pegehelper分页插件
    webmagic之爬取数据存储为TXT
  • 原文地址:https://www.cnblogs.com/skyfreedom/p/4775314.html
Copyright © 2011-2022 走看看