然后来看看ToUpper的实现:
private static bool ImplementByToUpper(List<string> strs, string value)
{
for (int i = 0; i < strs.Count; i++)
if (value.ToUpper() == strs[i].ToUpper())
return true;
return false;
}
{
for (int i = 0; i < strs.Count; i++)
if (value.ToUpper() == strs[i].ToUpper())
return true;
return false;
}
最后准备好main方法:
List<string> strs = CreateStrings();
bool result;
Console.WriteLine("Use ImplementByToUpper");
result = MeasurePerformance(s => ImplementByToUpper(strs, s), "yZh", 1000);
Console.WriteLine("result is " + result.ToString());
Console.ReadLine();
bool result;
Console.WriteLine("Use ImplementByToUpper");
result = MeasurePerformance(s => ImplementByToUpper(strs, s), "yZh", 1000);
Console.WriteLine("result is " + result.ToString());
Console.ReadLine();
来看看执行结果:
Use ImplementByToUpper
2192ms
GC 0:247
GC 1:0
GC 2:0
result is True
2192ms
GC 0:247
GC 1:0
GC 2:0
result is True
来个对比测试,用string.Equals来测试一下:
private static bool ImplementByStringEquals(List<string> strs, string value)
{
for (int i = 0; i < strs.Count; i++)
if (string.Equals(value, strs[i], StringComparison.CurrentCultureIgnoreCase))
return true;
return false;
}
{
for (int i = 0; i < strs.Count; i++)
if (string.Equals(value, strs[i], StringComparison.CurrentCultureIgnoreCase))
return true;
return false;
}
来看看执行结果:
Use ImplementByStringEquals
1117ms
GC 0:0
GC 1:0
GC 2:0
result is True
1117ms
GC 0:0
GC 1:0
GC 2:0
result is True
对比一下,使用ToUpper的速度要慢一倍,并且有大量的0代垃圾对象。那些号称是用空间换时间的人可以反思一下了,用空间换来了什么?负时间吗?