【发布时间】:2015-03-04 00:58:06
【问题描述】:
我正在为我的 ASP.NET 服务器实现字数统计功能,我想知道这样做的最快方法是什么,因为我不确定是否使用简单
text.AsParallel().Count(Char.IsWhiteSpace);
是最快的方法。由于此功能可能会在相对较长的文本墙上使用相当多,因此我希望它尽可能快,即使这意味着使用不安全的方法。
编辑:使用 Rufus L 的代码以及我自己的不安全方法进行一些基准测试:
public static unsafe int CountWords(string s)
{
int count = 0;
fixed (char* ps = s)
{
int len = s.Length;
char* pc = ps;
while (len-- > 0)
{
if (char.IsWhiteSpace(*pc++))
{
count++;
}
}
}
return count;
}
Split(null):681979 个单词,415867 个刻度。
Count(WhiteSpace):681978 个单词,147860 个刻度。
AsParallel:401077 个刻度中的 681978 个单词。
不安全:681978 个单词,98139 个刻度。
我仍然对任何更好的想法持开放态度:)
EDIT2:
重写函数,同时处理多个空格:
public static unsafe int CountWords(string s)
{
int count = 0;
fixed (char* ps = s)
{
int len = s.Length;
bool inWord = false;
char* pc = ps;
while (len-- > 0)
{
if (char.IsWhiteSpace(*pc++))
{
if (!inWord)
{
inWord = true;
}
}
else
{
if (inWord)
{
inWord = false;
count++;
}
}
if (len == 0)
{
if (inWord)
{
count++;
}
}
}
}
return count;
}
Split(null):681979 个单词,517055 个刻度。
Count(WhiteSpace):681978 个单词,148952 个刻度。
AsParallel:681978 个单词,410289 个刻度。
不安全:660000 个单词,114833 个刻度。
【问题讨论】:
-
两点 1) 先做基准。它是线性且便宜的,即使在“长长的文本墙”上也意味着非常非常快 2) AsParallel 在服务器端应用程序上没有多大意义。
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# asp.net performance optimization count