分类目录

链接

2011 年 12 月
 1234
567891011
12131415161718
19202122232425
262728293031  

近期文章

热门标签

新人福利,免费薅羊毛

现在位置:    首页 > .NET > 正文
代码优化之类型性能
.NET 暂无评论 阅读(1,875)

撇开那些文章不说,C#/.NET慢似乎是业界公认的铁则,不论大家如何证明C# / .NET其实不比C++慢多少,但是应用程序级别的性能却依然这么慢。

那么C#/.NET慢在哪里?

很不幸的是大部分c#程序是被大部分程序员拖慢的,也许这个结论不太容易被人接受,却是一个广泛存在的。

  String的操作

几乎所有的程序都有String操作,至少90%的程序需要忽略大小写的比较,检查一下代码,至少其中大半的应用程序有类似这样的代码:

if (str1.ToUpper() == str2.ToUpper())

或者ToLower版的,甚至我还看到过有个Web的HttpModule里面写上了:

for (int i = 0; i < strs.Count; i++)
if (value.ToUpper() == strs[i].ToUpper())
//...

想一下,每个页面请求过来,都要执行这样一段代码,大片大片的创建string实例,更夸张的是还有人说这是用空间换时间。

  性能测试

说这个方法慢,也许还有人不承认,认为这个就是最好的方法,所以这里要用具体测试来摆个事实。

首先准备一个测试性能的方法:

PRivate static TResult MeasurePerformance<TArg, TResult>(Func<TArg, TResult> func, TArg arg, int loop)
{
GC.Collect();
int gc0 = GC.CollectionCount(0);
int gc1 = GC.CollectionCount(1);
int gc2 = GC.CollectionCount(2);
TResult result = default(TResult);
Stopwatch sw = Stopwatch.StartNew();
for (int i = 0; i < loop; i++)
{
result = func(arg);
}
Console.WriteLine(sw.ElapsedMilliseconds.ToString() + "ms");
Console.WriteLine("GC 0:" + (GC.CollectionCount(0) - gc0).ToString());
Console.WriteLine("GC 1:" + (GC.CollectionCount(1) - gc1).ToString());
Console.WriteLine("GC 2:" + (GC.CollectionCount(2) - gc2).ToString());
return result;
}

然后来准备一个堆string:

private static List<string> CreateStrings()
{
List<string> strs = new List<string>(10000);
char[] chs = new char[3];
for (int i = 0; i < 10000; i++)
{
int j = i;
for (int k = 0; k < chs.Length; k++)
{
chs[k] = (char)('a' + j % 26);
j = j / 26;
}
strs.Add(new string(chs));
}
return strs;
}

 

然后来看看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;
}

最后准备好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();

来看看执行结果:

Use ImplementByToUpper
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;
}

来看看执行结果:

Use ImplementByStringEquals
1117ms
GC 0:0
GC 1:0
GC 2:0
result is True

对比一下,使用ToUpper的速度要慢一倍,并且有大量的0代垃圾对象。那些号称是用空间换时间的人可以反思一下了,用空间换来了什么?负时间吗?

 

  字典类的使用

继续说string的场景,有些人也许会想到用Hash表等类似结构来加速,不错,这是个好主意,只不过,Hash表不一定总是最佳方案,什么不相信?还是做个测试吧:

private static bool ImplementByHashSet(List<string> strs, string value)
{
HashSet<string> set = new HashSet<string>(strs, StringComparer.CurrentCultureIgnoreCase);
return set.Contains(value);
}

看看执行结果:

Use ImplementByHashSet
5114ms
GC 0:38
GC 1:38
GC 2:38
result is True

惊讶吧,速度比用ToUpper还慢了1倍多,而且2代垃圾也38次的回收(执行2代垃圾回收时,会强制执行1代和0代垃圾回收)。

不过使用Hash表等类似来加速这个想法本身是一个很正确的想法,不过前提是Hash表本身能够缓存,例如:

private static Func<string, bool> ImplementByHashSet2(List<string> strs)
{
HashSet<string> set = new HashSet<string>(strs, StringComparer.CurrentCultureIgnoreCase);
return set.Contains;
}

然后把main的方法修改为:

Console.WriteLine("Use ImplementByHashSet2");
result = MeasurePerformance(s =>
{
var f = ImplementByHashSet2(strs);
bool ret = false;
for (int i = 0; i < 1000; i++)
{
ret = f(s);
}
return ret;
}, "yZh", 1);
Console.WriteLine("result is " + result.ToString());
Console.ReadLine();

再看看结果:

Use ImplementByHashSet2
6ms
GC 0:0
GC 1:0
GC 2:0
result is True

性能出现了飞跃性的增长。

  更 多

是什么拖慢了C#/.NET?简单的说:不必要的创建对象,不必要的同步,循环执行低效的方法(例如被firelong重点批斗的反射,不过ms并没让你在循环里面使用Invoke),使用低效的数据结构和算法(看看缓存情况下Hash表类似结构的惊人表现,就知道区别了)。

C#/.NET的低门槛确实在一定程度上有利于把更多的程序员拉入C#/.NET,但是也确实把整个C#/.NET程序的代码水平降低了不少,这一点确实很令人担忧。

最后别忘了一点,一个系统能有多少性能,不是由这个系统中性能最好的部分决定的,而是由这个系统中性能最差的部分所决定的。配一台有16g内存,100t硬盘,加上顶级的显卡,缺配上386的cpu,这台电脑的性能就是386的性能。同样,C#/.NET再好,写程序的人水平差,写出来的程序的性能自然也就差了。

============ 欢迎各位老板打赏~ ===========

本文版权归Bruce's Blog所有,转载引用请完整注明以下信息:
本文作者:Bruce
本文地址:代码优化之类型性能 | Bruce's Blog

发表评论

留言无头像?