学习笔记: 泛型

List<object> 与 List<T> 区别

object类型参数有2个问题:
1 装箱拆箱,性能损耗
   传入一个int值(栈)
   object又在堆里面,如果把int传递进来,就会把值从栈里面copy到堆里
   使用的时候,又需要用对象值,又会copy到栈(拆箱)

2 类型安全问题,可能会有,因为传递的对象是没有限制的

image

泛型方法与普通方法性能对比

public class Monitor
{
     public static void Show()
     {
         Console.WriteLine("****************Monitor******************");
         {
             int iValue = 12345;
             long commonSecond = 0;
             long objectSecond = 0;
             long genericSecond = 0;

            {
                 Stopwatch watch = new Stopwatch();
                 watch.Start();
                 for (int i = 0; i < 100_000_000; i++)
                 {
                     ShowInt(iValue);
                 }
                 watch.Stop();
                 commonSecond = watch.ElapsedMilliseconds;
             }
             {
                 Stopwatch watch = new Stopwatch();
                 watch.Start();
                 for (int i = 0; i < 100_000_000; i++)
                 {
                     ShowObject(iValue);
                 }
                 watch.Stop();
                 objectSecond = watch.ElapsedMilliseconds;
             }
             {
                 Stopwatch watch = new Stopwatch();
                 watch.Start();
                 for (int i = 0; i < 100_000_000; i++)
                 {
                     Show<int>(iValue);
                 }
                 watch.Stop();
                 genericSecond = watch.ElapsedMilliseconds;
             }
             Console.WriteLine("commonSecond={0},objectSecond={1},genericSecond={2}"
                 , commonSecond, objectSecond, genericSecond);
         }
     }

    #region PrivateMethod
     private static void ShowInt(int iParameter)
     {
         //do nothing
     }
     private static void ShowObject(object oParameter)
     {
         //do nothing
     }
     private static void Show<T>(T tParameter)
     {
         //do nothing
     }
     #endregion

}

image

泛型方法与普通方法性能一致,还能一个方法满足多个不同类型

object方法性能低: int 与 object 频繁装箱拆箱


泛型缓存

/// <summary>
/// 每个不同的T,都会生成一份不同的副本
/// 适合不同类型,需要缓存一份数据的场景,效率高
/// </summary>
/// <typeparam name="T"></typeparam>
public class GenericCache<T>
{
     static GenericCache()
     {
         Console.WriteLine("This is GenericCache 静态构造函数");
         _TypeTime = string.Format("{0}_{1}", typeof(T).FullName, DateTime.Now.ToString("yyyyMMddHHmmss.fff"));
     }

    private static string _TypeTime = "";

    public static string GetCache()
     {
         return _TypeTime;
     }
     //common<int>(1)
}

posted @ 2019-04-07 12:54  小谭行天下  阅读(152)  评论(0编辑  收藏  举报