日期:2009-08-11  浏览次数:20463 次

1.GetGBLength()
/**//// <summary>
/// 菜菜写的
/// </summary>
private static int GetGBLengthC(string strData)

{
int iLen = 0;
if( strData!=null || strData!="")
{
try
{
iLen = System.Text.Encoding.Default.GetByteCount(strData);
}
catch{}
}
return iLen;
}
2.GetGBLengthA()
/**//// <summary>
/// 风@(((((
/// </summary>
private static int GetGBLengthA(string strData)
{
System.Text.Encoding encoder5 = System.Text.Encoding.GetEncoding("GB2312");
return encoder5.GetByteCount(strData);
}

3.GetGBLengthB /**//// <summary>
/// 活靶子.Net
/// </summary>
private static int GetGBLengthB(string Str)
{
int intResult = 0;
foreach (char Char in Str)
{
if ((int)Char > 127)
intResult += 2;
else
intResult ++;
}
return intResult;


测试主程序:
static void Main(string[] args)
{
StopWatch sw = new StopWatch();
string strData = "01234567890阿发端发;立法局阿;领导法拉第发端夫君阿;地方阿斗发狂三角枫哈萨克毒发啊发狂挥发可回到发阿克苏多幅阿抗倒伏阿括弧发狂复活卡哈喀什发咖啡阿卡罚款罚款发狂撒发狂撒发狂撒多幅阿卡大饭卡大发狂撒毒发阔的饭卡大饭卡大饭卡大饭卡大发狂撒多幅阿克苏大罚款毒发阔的发咔哒复活卡多幅卡多幅卡撒多幅卡撒多幅哈克三点会发阿抗倒伏阿克苏多幅阿卡饭卡大akdfhaksdjfha kdfa ";
for( int i=0; i<10; i++ )
strData +=strData;
GC.Collect();

sw.Reset();
GetGBLengthA(strData);
Console.WriteLine("GetGBLengthA() Run Time: " + (sw.Peek() / (float)1000).ToString() + " 毫秒");

sw.Reset();
GetGBLengthB(strData);
Console.WriteLine("GetGBLengthB() Run Time: " + (sw.Peek() / (float)1000).ToString() + " 毫秒");

sw.Reset();
GetGBLengthC(strData);
Console.WriteLine("GetGBLengthC() Run Time: " + (sw.Peek() / (float)1000).ToString() + " 毫秒");
}

测试字符串长度364544,编译成Release版本运行10次,取第10次作为统计结果。
统计结果如下:
GetGBLengthA() Run Time: 2.252 毫秒
GetGBLengthB() Run Time: 0.871 毫秒
GetGBLengthC() Run Time: 2.127 毫秒