指针 for循环 foreach 以及 lamda 的性能比较.

var count = 10000 * 10000;

//几种写法
/*
* if (*pb++ == fn)
* if (li[i] == fn)
* if (i == fn)
* li.First(j => j == fn);
*/

var li = new int[count];
for (var i = 0; i < count; i++)
{
li[i] = i;
}
count = li.Length;

var s = "";

var fn = li.Last();

var sw = new Stopwatch();

sw.Start();

fixed (int* _pb = li)
{
int* pb = _pb;

for (int i = 0; i < count; i++)
{
if (*pb++ == fn)
break;
}
}

s += "\r\n指针 \t" + sw.ElapsedMilliseconds;

sw.Restart();

for (int i = 0; i < count; i++)
{
if (li[i] == fn)
{
break;
}
}

s += "\r\nFor循环 \t" + sw.ElapsedMilliseconds;

sw.Restart();
foreach (var i in li)
{
if (i == fn)
{
break;
}
}

s += "\r\nForeach \t" + sw.ElapsedMilliseconds;

sw.Restart();
li.First(j => j == fn);

s += "\r\nLamda \t" + sw.ElapsedMilliseconds;

MessageBox.Show(s);

结果

 
 
 
指针直接访问内存,做的是最基础的运算,最快.

for循环 有下标 堆栈消耗+1

foreach Call NextElement 堆栈消耗 +1

lamda 用foreach 调用 func 堆栈消耗 +2

posted on 2012-02-09 13:45  Terry@  阅读(2071)  评论(0编辑  收藏  举报

导航