泛型反射性能優化

一,泛型反射優化:基本思路,根據泛型緩存原理(靜態構造+靜態字段)緩存

   public class Accessor<S>
    {
        /// <summary>
        /// 屬性類型
        /// </summary>
        public static PropertyInfo[] PropertyTypes { get; private set; }
        /// <summary>
        /// 實體類型
        /// </summary>
        public static Type type { get; private set; }

        static Accessor()
        {
            type = typeof(S);
            PropertyTypes = type.GetProperties();
        }
    }

二,調用邏輯優化

 Stopwatch st = new Stopwatch();
            st.Start();

            for (int i = 0; i < 10000000; i++)
            {
                var ss = Accessor<Person>.PropertyTypes;
            }
            st.Stop();
            var str1 = st.ElapsedMilliseconds.ToString();


            st.Reset();
            st.Start();
            for (int i = 0; i < 10000000; i++)
            {
                Type type = typeof(Person);
                var ss = type.GetProperties();
            }
            st.Stop();
            var str2 = st.ElapsedMilliseconds.ToString();
相關文章
相關標籤/搜索