Fork me on github

c# "As" 与 "Is"效率 (原发布csdn 2017-10-07 11:49:18)

十一长假就要过去了,今年假期没有回家,一个人闲着无聊就在看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 obj = i + 1;
            if (obj 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 obj = i + 1;
            TestIntType = obj 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 obj = testClass;
            if (obj is TestClass)
            {
                TestClass objTest = (TestClass)obj;
            }
        }
        sw_Timer.Stop();
        Console.WriteLine("Is运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
        
        sw_Timer.Restart();
        for (int i = 0; i < NUM; i++)
        {
            object obj = testClass;
            TestClass objTest = obj as TestClass;
            if (objTest != null)
            {
                
            }
        }
        sw_Timer.Stop();
        Console.WriteLine("As运算{0}次所需时间,{1}Ticks.", NUM, sw_Timer.ElapsedTicks);
        
        Console.ReadKey();
    }
}

测试结果这里写图片描述

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

posted @ 2019-09-05 19:26  njit_77  阅读(499)  评论(0编辑  收藏  举报