这个的效率是多少?...
CommentText.ToCharArray().Where(c => c >= 'A' && c <= 'Z').Count()
好的,我刚编写了一些代码来计算你的方法所需的时间:
int count = 0;
for (int i = 0; i < s.Length; i++)
{
if (char.IsUpper(s[i])) count++;
}
结果:
你的: 19737 ticks
我的: 118 ticks
相差很大!有时候最直接的方式也是最有效的。
编辑
只是出于兴趣,这个:
int count = s.Count(c => char.IsUpper(c));
该操作大约需要2500个时钟周期。因此,对于使用Linq一行代码的操作来说,速度相当快。
首先,你没有理由调用ToCharArray()
方法,因为假设CommentText
是一个字符串,它已经是一个IEnumerable<char>
。其次,你应该使用char.IsUpper
方法,而不是假设你只处理ASCII值。代码应该像这样:
CommentText.Count(char.IsUpper)
int count = 0;
for (int i = 0; i < CommentText.Length; i++)
if (char.IsUpper(CommentText[i]) count++;
一般来说,调用任何方法都比内联代码慢,但这种优化只应在您绝对确定这是代码的瓶颈时进行。
您只计算了标准ASCII码,而没有考虑到像ÃÐÊ等字符。
那么如何解决呢?
CommentText.ToCharArray().Where(c => Char.IsUpper(c)).Count()
我甚至没有测试,但我会说
int count = 0;
foreach (char c in commentText)
{
if (Char.IsUpper(c))
count++;
}
现在关闭了,测试看看是否更快。
CommentText.Count(c => Char.IsUpper(c))
编辑:根据Matt的建议,也删除了ToCharArray调用。
I've got this
Regex x = new Regex("[A-Z]{1}",
RegexOptions.Compiled | RegexOptions.CultureInvariant);
int c = x.Matches(s).Count;
但我不知道它是否特别快。它也不能获取特殊字符,我想
编辑:
与此问题答案的快速比较。在vshost中进行调试,使用字符串进行10,000次迭代:
aBcDeFGHi1287jKK6437628asghwHllmTbynerA
Regex.Matches(s, "[A-Z]{1}", RegexOptions.Compiled | RegexOptions.CultureInvariant).Count;
- Mike Christian