4)继续优化――用空间换取时间
现在对每一个字符,都要用get_Item(object key)方法过一遍,可这个乖乖方法那么长,肯定太耗时间了,能不能用更简单的手段呢?改Hashtable?哇,那代码,叫一个看不懂。仔细琢磨琢磨,有了,直接用数组!每一个汉字对应一个Int16,以该值为索引,数组中在那个位置的值为值,这样最快速了。就是占点空间,内存便宜嘛。反正这东西只初始化一次,占不了多少k。新程序如下:
1 public class QuickChineseConvert 2 { 3 static char[] _lib; 4 static int _size; 5 6 static QuickChineseConvert() 7 { 8 _size=UInt16.MaxValue; 9 Init(); 10 } 11 static string GB_lib="……"; 12 static string BIG5_lib="……"; 13 14 private static void PushIntoArray(char[] c , string g, string b) 15 { 16 for (int i=0;i<g.Length;i++) 17 { 18 c[Convert.ToUInt16(g[i])]=b[i]; 19 } 20 } 21 22 private static void Init() 23 { 24 _lib = new char[_size]; 25 PushIntoArray(_lib,GB_lib,BIG5_lib); 26 } 27 28 public static char ToBIG5(char inputChar) 29 { 30 char temp = _lib[Convert.ToUInt16(inputChar)]; 31 return temp==0?inputChar:(char)temp; 32 } 33 34 public static string ToBIG5(string inputString) 35 { 36 StringBuilder sb = new StringBuilder(); 37 for (int i=0;i<inputString.Length;i++) 38 { 39 sb.Append(ToBIG5(inputString[i])); 40 } 41 return sb.ToString(); 42 } 43 } |
这样的话,对于每一个字符,只进行几个简单的操作了:
Convert.ToUInt16(inputChar)
从数组中取值_lib[Convert.ToUInt16(inputChar)]
然后就是return temp==0?inputChar:(char)temp;
对比Hashtable臭长臭长的get_Item(object key),这下简单多了!当然,要付出一定代价,代价就是要弄一个大小为UInt16.MaxValue的数组,不大嘛。
测试性能,很鼓舞人心:1857万字/s