一直以为C#中的switch语句在处理字符串时是用if语句来构造的,因为.net的IL中的switch也逃不脱C的宿命--只能
处理数字,而实际上C#编译器对switch语句对字符串的处理却让人汗啊.
首先编译一下下面的代码:
;
EntryPoint
{
Main()
{
Console.WriteLine();
szInput = Console.ReadLine();
(szInput)
{
:
Console.WriteLine();
;
:
Console.WriteLine();
;
:
Console.WriteLine();
;
:
Console.WriteLine();
;
:
Console.WriteLine();
;
:
Console.WriteLine();
;
:
Console.WriteLine(,szInput);
;
}
Console.Read();
}
}
再用Reflector反编译上面源代码编译出来的程序,下面是反编译出来的代码
Main()
{
Console.WriteLine();
text1 = Console.ReadLine();
text2 = text1;
(text2 != )
{
num2;
(<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}.$method0x6000001- == )
{
Dictionary<string, > dictionary1 = Dictionary<string, >();
dictionary1.Add(, );
dictionary1.Add(, );
dictionary1.Add(, );
dictionary1.Add(, );
dictionary1.Add(, );
dictionary1.Add(, );
<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}.$method0x6000001- = dictionary1;
}
(<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}.$method0x6000001-.TryGetValue(text2, num2))
{
(num2)
{
:
Console.WriteLine();
Label_0105;
:
Console.WriteLine();
Label_0105;
:
Console.WriteLine();
Label_0105;
:
Console.WriteLine();
Label_0105;
:
Console.WriteLine();
Label_0105;
:
Console.WriteLine();
Label_0105;
}
}
}
Console.WriteLine(, text1);
Label_0105:
Console.Read();
}
可以看到C#编译器把所有case标签里的字符串按顺序存储到泛型的字典$method0x6000001-1中(键是标签值,值是标签序号
).而$method0x6000001-1则是<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}类中的一个静态
字段.下面是<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}的代码
[CompilerGenerated]
<PrivateImplementationDetails>{FEB70444-128D-453C-8E6F-C839E1DC2F51}
{
Dictionary<string, > $method0x6000001-;
}
用过VC的人可能知道在VC中当swith语句中的标签大于一定的数量时VC编译器会建立一个散列表来提升case标签的查找性能
.呵呵!没想到这个思想在如今的C#编译器中也得到了应用,真让人喜出望外啊!
或许有人会认为以上的代码多了一个字典字段的初始化而switch中的标签也并没有削减可能反而会影响了性能.这些不必担
忧因为:
,由于Dictionary的存储结构是散列结构,所以它查找起起数据来;
,switch语句在IL中是直接支持的,所以不用过滤;
,Dictionary字段是一个静态字段,只须初始化一次;
,俺们挖空心思的优化自己的代码,还不如编译器的优化好(失败的打击).
但是,正如VC编译器一样C#编译器并不会对所有的字符串的swith语句都用字典来存储,而是当case标签的数量在>=6个时才
用字典来提升查找性能.
注意:以上的代码如果用C#.0编译将会有所差异其中用来存储标签中的字符串的对象不是Dictionary而是HashTable.
---------------------
作者:gu_fan
来源:优快云
原文:https://blog.youkuaiyun.com/gu_fan/article/details/821049
版权声明:本文为博主原创文章,转载请附上博文链接!
C#对switch语句的优化
最新推荐文章于 2025-02-21 19:33:29 发布