好 - 时间为新的真相!
这是对字符串中任何大写字母的测试。
该字符串保证在第一个60K字符内没有任何大写字符。 (我从random.org创建的字符串)
我通过随机化将64K字符串传递给测试函数来防止编译器中的字符串替换优化。
所有的时间都非常严格地围绕实际测试,并且不包括函数调用时间。
我跑了测试一次,10次,并再次10000次,并平均每组测试的时间。
我跑在64位的测试运7与i3-2100 CPU @ 3.1千兆赫
试验例1:
static bool testCaseOne(string str, out double ms)
{
bool result = false;
DateTime start = DateTime.Now;
result = !string.IsNullOrEmpty(str) && str.Any(c => char.IsUpper(c));
ms = (DateTime.Now - start).TotalMilliseconds;
return result;
}
得到的平均时间:
- 1 X = 3.000 ms
- 10 x = 0.860 ms
- 10,000 x = 0。821毫秒
试验例2:
static bool testCaseTwo(string str, out double ms)
{
bool result = false;
DateTime start = DateTime.Now;
if (string.IsNullOrEmpty(str))
{
ms = 0;
return false;
}
result = Regex.IsMatch(str, "[A-Z]");
ms = (DateTime.Now - start).TotalMilliseconds;
return result;
}
得到的平均时间:
- 1×= 2.000毫秒
- 10×= 1.597毫秒
- 10,000×= 1.603毫秒
试验例3:
static bool testCaseThree(string str, out double ms)
{
bool result = false;
DateTime start = DateTime.Now;
if (string.IsNullOrEmpty(str))
{
ms = 0;
return false;
}
for (int i = 0; i < str.Length; i++)
{
if (char.IsUpper(str[i]))
{
result = true;
break;
}
}
ms = (DateTime.Now - start).TotalMilliseconds;
return result;
}
得到的平均时间:
- 1×= 1.000毫秒
- 10×= 0.357毫秒
- 10,000×= 0.298毫秒
测试案例4:
static bool testCaseFour(string str, out double ms)
{
bool result = false;
DateTime start = DateTime.Now;
if (string.IsNullOrEmpty(str))
{
ms = 0;
return false;
}
for (int i = 0; i < str.Length; i++)
{
if (str[i] > 64 && str[i] < 91)
{
result = true;
break;
}
}
ms = (DateTime.Now - start).TotalMilliseconds;
return result;
}
}
得到的平均时间:
- 1×= 0.000毫秒
- 10×= 0.137毫秒
- 10,000×= 0.184毫秒
有趣。
我希望这statisfies RK先生;)
我会考虑这个“足够快”。 – BoltClock 2011-06-01 01:19:21
我认为这是一个好方法,你可以使用LINQ来完成for循环的工作,但生成的代码将是等效的。您还可以测试原始字符串是否与转换为小写字符串的字符串不相同,但是我期望该字符串的性能较差,因为它始终需要全部遍历字符串。 – Clayton 2011-06-01 01:23:58
使用LINQ代替for循环可能会出现一些性能问题 – VisualBean 2013-10-08 12:40:18