取枚举值和枚举名几种方法效率测试

测试代码
        private static void Test2(int count)
        {
            int a = 0, b = 0;
            string c=string.Empty, d=string.Empty;
            DateTime dt1 = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                a = (int)SystemUserRole.教师;
                //Console.WriteLine(i + "\t(int):" + a);
            }
            DateTime dt2 = DateTime.Now;

            DateTime dt3 = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                b = SystemUserRole.教师.GetHashCode();
                //Console.WriteLine(i + "\tGetHashCode():" + b);
            }
            DateTime dt4 = DateTime.Now;

            DateTime dt5 = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                c = SystemUserRole.教师.ToString();
                //Console.WriteLine(i + "\tToString():" + SystemUserRole.教师.ToString());
            }
            DateTime dt6 = DateTime.Now;

            DateTime dt7 = DateTime.Now;
            for (int i = 0; i < count; i++)
            {
                d = Enum.GetName(typeof(SystemUserRole), (int)SystemUserRole.教师);
                //Console.WriteLine(i + "\tEnum.GetName:" + Enum.GetName(typeof(SystemUserRole), (int)SystemUserRole.教师));
            }
            DateTime dt8 = DateTime.Now;

            Console.WriteLine(a+"\t强制转换枚举值执行时长:" + (dt2 - dt1).ToString());
            Console.WriteLine(b+"\tGetHashCode()取枚举值执行时长:" + (dt4 - dt3).ToString());
            Console.WriteLine(c+"\tToString()取枚举名执行时长:" + (dt6 - dt5).ToString());
            Console.WriteLine(d+"\tEnum.GetName取枚举名执行时长:" + (dt8 - dt7).ToString());
            Console.Read();
        }
 
枚举代码
    /// <summary>
    /// 系统用户角色
    /// </summary>
    public enum SystemUserRole
    {
        超级管理员 = 1,
        视频筛选员 = 2,
        琴行 = 3,
        教师 = 4,
        求职用户 = 5,
        学员 = 6,
        测试用户 = 7
    }
 
 
调用代码
        static void Main(string[] args)
        {
            //NewMethod();
            int count = 100000000;
            //Test1(count / 1000); //太大了时间太长
            Test2(count);
        }
 
执行结果




posted @ 2013-05-18 01:05  Adming  阅读(586)  评论(0编辑  收藏  举报