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

匿名 (未验证) 提交于 2019-12-02 22:09:29
if(obj is T) {     T value = (T) obj; }

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

测试例子:

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();     } }

测试结果

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!