几种获得中英文混合字符串长度方法的性能比较
2007-03-29 01:32
656 查看
闲来无聊,写了几个获得中英文混合字符串长度的方法,在性能上做了简单的比较,希望对大家有所帮助
namespace Socg
{
/// <summary>
/// 获得中英文混合字符串的长度
/// </summary>
public class Lenght
{
/// <summary>
/// 利用 正则表达式
/// </summary>
public static int Lenght1(string str)
{
return str.Length+ Regex.Matches(str,"[/u0080-/uffff]").Count;
}
/// <summary>
/// 利用 Encoding
/// </summary>
public static int Lenght2(string str)
{
return System.Text.Encoding.Default.GetBytes(str).Length;;
}
/// <summary>
/// 循环判断
/// </summary>
public static int Lenght3(string str)
{
int len = str.Length;//用于返回的长度
int len2 = str.Length;//临时存放 str.Length,在循环中平凡使用,这样比直接使用 str.Length 要快
for(int i=0;i<len2;i++)
{
if(str[i]>127)len++;
}
return len;
}
/// <summary>
/// 利用指针循环判断
/// </summary>
unsafe public static int Lenght4(string str)
{
int len = str.Length;//用于返回的长度
int i = len;//计数器
fixed(char* pstr = str)
{
char* pstr2 = pstr;
while(i-- > 0)
{
if(*pstr2 > 127) len++;
pstr2++;
}
}
return len;
}
}
}
测试:长度为100的比较随机的字符串,1000000次所用的时间
Lenght1(正则表达式)----------------245.4 秒 完全不可取(本人正则表达式是外行,如果有效率更高的方法请指正)
Lenght2(利用Encoding)-------------4.03秒 最.Net的方法,可惜不是最快的
Lenght3(循环判断)------------------1.36秒 最老实的方法,性能也比较好
Lenght4(利用指针循环判断)-----------0.64秒 最变态的方法,在速度上无话可说,但是需要/unsafe选项才能编译通过
namespace Socg
{
/// <summary>
/// 获得中英文混合字符串的长度
/// </summary>
public class Lenght
{
/// <summary>
/// 利用 正则表达式
/// </summary>
public static int Lenght1(string str)
{
return str.Length+ Regex.Matches(str,"[/u0080-/uffff]").Count;
}
/// <summary>
/// 利用 Encoding
/// </summary>
public static int Lenght2(string str)
{
return System.Text.Encoding.Default.GetBytes(str).Length;;
}
/// <summary>
/// 循环判断
/// </summary>
public static int Lenght3(string str)
{
int len = str.Length;//用于返回的长度
int len2 = str.Length;//临时存放 str.Length,在循环中平凡使用,这样比直接使用 str.Length 要快
for(int i=0;i<len2;i++)
{
if(str[i]>127)len++;
}
return len;
}
/// <summary>
/// 利用指针循环判断
/// </summary>
unsafe public static int Lenght4(string str)
{
int len = str.Length;//用于返回的长度
int i = len;//计数器
fixed(char* pstr = str)
{
char* pstr2 = pstr;
while(i-- > 0)
{
if(*pstr2 > 127) len++;
pstr2++;
}
}
return len;
}
}
}
测试:长度为100的比较随机的字符串,1000000次所用的时间
Lenght1(正则表达式)----------------245.4 秒 完全不可取(本人正则表达式是外行,如果有效率更高的方法请指正)
Lenght2(利用Encoding)-------------4.03秒 最.Net的方法,可惜不是最快的
Lenght3(循环判断)------------------1.36秒 最老实的方法,性能也比较好
Lenght4(利用指针循环判断)-----------0.64秒 最变态的方法,在速度上无话可说,但是需要/unsafe选项才能编译通过
相关文章推荐
- 对几种获取字符串长度的方法进行性能比较
- 测试了3种获取中英文混合字符串长度的方法
- javascript获取中英文混合字符串的长度方法
- JavaScript获取中英文混合字符串长度的方法示例
- java几种切割字符串方法的性能比较
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- PHP针对中英文混合字符串长度判断及截取方法
- 【原】检测是否包含特定字符串的几种方法以及性能比较
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- 测试了3种获取中英文混合字符串长度的方法,看来还是使用循环来的快
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- iOS计算中英文混合字符串长度的方法
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- PHP针对中英文混合字符串长度判断及截取方法示例
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- C#实现 获取指定字节长度 中英文混合字符串 的方法
- C#与JS实现 获取指定字节长度 中英文混合字符串 的方法
- 3种获取中英文混合字符串长度的方法
- 中英文混合字符串判定长度方法