本文最后更新于 2025-11-16 22:09:22
十一长假就要过去了,今年假期没有回家,一个人闲着无聊就在看C#语言规范5.0中文版。昨天看了 is运算符和 as运算符,平时项目中也有用到这两种符号,对于其效率也没有进行比较过,趁着假期有空,先看下效率。
is 常用法:
1 2 3 4
| if(obj is T) { T value = (T) obj; }
|
先判断obj是不是T类型,如果是再进行转换。
as 常用法:
1 2 3 4 5
| 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 变量仅进行一次计算。


测试例子:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69
| class TestClass {
}
class Program { static Stopwatch sw_Timer = new Stopwatch(); const int NUM = 100_000; 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(); } }
|
测试结果

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