c# "As" 与 "Is"效率

来源:互联网 发布:java 获取服务器ip 编辑:程序博客网 时间:2024/05/18 00:03

十一长假就要过去了,今年假期没有回家,一个人闲着无聊就在看C#语言规范5.0中文版。昨天看了 is运算符和 as运算符,平时项目中也有用到这两种符号,对于其效率也没有进行比较过,趁着假期有空,先看下效率。

is 常用法:

if(obj is T){    T value = (T) obj;}

先判断obj是不是T类型,如果是再进行转换。

这里写图片描述

as 常用法:

T value = obj as T;if(value !=null){}

如果obj不是T类型,value=null;如果是value=(T)obj。

expression as type 等同于expression is type ? (type)expression : (type)null 但 expression 变量仅进行一次计算。

这里写图片描述这里写图片描述

测试例子:

    class TestClass    {    }    class Program    {        static Stopwatch sw_Timer = new Stopwatch();        const int NUM = 100000;        static int? TestIntType;        static TestClass testClass = new TestClass();        static void Main()        {            Console.WriteLine("值类型测试.");            sw_Timer.Restart();            for (int i = 0; i < NUM; i++)            {                object obj1 = i + 1;                if (obj1 is int)                {                    TestIntType = (int?)obj1;                }            }            sw_Timer.Stop();            Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);            sw_Timer.Restart();            for (int i = 0; i < NUM; i++)            {                object obj2 = i + 1;                TestIntType = obj2 as int?;                if (TestIntType != null)                {                }            }            sw_Timer.Stop();            Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);            Console.WriteLine("引用类型测试.");            sw_Timer.Restart();            for (int i = 0; i < NUM; i++)            {                object obj3 = testClass;                if (obj3 is TestClass)                {                    TestClass obj4 = (TestClass)obj3;                }            }            sw_Timer.Stop();            Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);            sw_Timer.Restart();            for (int i = 0; i < NUM; i++)            {                object obj5 = testClass;                TestClass obj6 = obj5 as TestClass;                if (obj6 != null)                {                }            }            sw_Timer.Stop();            Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);            Console.ReadKey();        }    }

测试结果这里写图片描述

测试100000次,对于值类型,is>as;对于引用类型,as>is

原创粉丝点击