当前位置: 移动技术网 > IT编程>开发语言>.net > c# "As" 与 "Is"效率 (原发布csdn 2017-10-07 11:49:18)

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

2019年09月07日  | 移动技术网IT编程  | 我要评论

波光粼粼涟漪诊疗所,蕉下小黑伞,特种黑道

十一长假就要过去了,今年假期没有回家,一个人闲着无聊就在看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

如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网