Dotnet程序优化心得

发表于:2010-8-25 10:13

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:未知    来源:51Testing软件测试网采编

  测试性能,结果为300万字/秒。性能提高了10倍。

 1
 2Function B2G()Function B2G(prestr As String) As String
 3    Dim i, j As Integer
 4    Const GB_Lib = ""    //几千个字符吧,因为字符串长度限制,原程序是由GB_lib1,GB_lib2GB_lib4四个字符串构成的,为了简化问题,只用一个字符串代替。
 5    Const BIG5_Lib = ""    //与GB_Lib中简体字一一对应的繁体字
 6   
 7    For i = 1 To prestr.Length
 8        j= Instr(1, BIG5_Lib1, GetChar(prestr, i))
 9        If j<>0 Then prestr=prestr.Replace(GetChar(BIG5_Lib1,j),GetChar(GB_Lib1,j))
10        j= Instr(1, BIG5_Lib2, GetChar(prestr, i))
11        If j<>0 Then prestr=prestr.Replace(GetChar(BIG5_Lib2,j),GetChar(GB_Lib2,j))
12        j= Instr(1, BIG5_Lib3, GetChar(prestr, i))
13        If j<>0 Then prestr=prestr.Replace(GetChar(BIG5_Lib3,j),GetChar(GB_Lib3,j))
14        j= Instr(1, BIG5_Lib4, GetChar(prestr, i))
15        If j<>0 Then prestr=prestr.Replace(GetChar(BIG5_Lib4,j),GetChar(GB_Lib4,j))
16    Next
17    Return prestr
18End Function

  (2) 分析问题

  写测试程序测试在我的1.5M迅驰本本测试,替换效率为30万字/s,该程序采用Replace,这样对每一个字符都要扫描GB_Lib字符串中的几千个字符,性能自然上不去。需要寻找更好的数据结构和算法,降低每一个字符串的操作时间。

  .net类库里有一个很好的东西可以拿来直接用:Hashtable。也就是说,把每一个简体字作为key,每一个繁体字作为value。这样处理每个字符的时候只需要看它在不在Hashtable的key里面,在的话就找出对应的value替换,否则就不做任何操作。这样做的代价是Hashtable初始化的耗时,不过初始化顶多也就一次嘛。程序如下:

 1public class ConvertDemo
 2{
 3    private static Hashtable _libTable;
 4
 5    static ConvertDemo()
 6    {
 7        InitHashTable();
 8    }
 9
10    static string GB_lib="";
11
12    static string BIG5_lib="";
13
14    private static void InitHashTable()
15    {
16        _libTable = new Hashtable();
17        PushIntoHashtable(_libTable,GB_lib,BIG5_lib);
18    }
19
20    private static void PushIntoHashtable(Hashtable t, string g , string b)
21    {
22        for (int i=0;i<g.Length;i++)
23        {
24            t.Add(g[i],b[i]);
25        }
26    }
27
28    private static char ConvertChar(char input)
29    {
30        if (_libTable.ContainsKey(input)) return (char)_libTable[input];
31        else return input;
32    }
33
34    public static string ConvertText(string inputString)
35    {
36        StringBuilder sb = new StringBuilder(inputString);
37        for (int i=0;i<inputString.Length;i++)
38        {
39            sb[i] = ConvertChar(inputString[i]);
40        }
41        return sb.ToString();
42    }
43}

62/6<123456>
《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号