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