您的位置:首页 > 编程语言 > C#

C# foreach,linq,delegate集合查询的性能比较

2011-11-04 11:11 375 查看
因为前面,叶鹏(http://www.cnblogs.com/jqbird/archive/2011/11/04/2235627.html 已经做过测试,我只是重新验证了一下,发现他的结果是不对的。我得出的结果是,foreach > delegate > linq,这个是我反复测试的结果

代码和他的差不多

public class TestClass
{
public int Id
{
get;
set;
}
public string Name
{
get;
set;
}
}

static void Main(string[] args)
{
test();
}

private static void test()
{
IList<TestClass> list1 = new List<TestClass>();

for (int i = 0; i < 10000000; i++)
{
TestClass tc = new TestClass();
tc.Id = i;
tc.Name = "Test Data" + i;
list1.Add(tc);
}

Stopwatch timer = new Stopwatch();

#region for circle
timer.Start();
int count = 0;
foreach (TestClass tc in list1)
{
if (1 <= tc.Id && tc.Id < 1000)
{
count++;
}
}
timer.Stop();

Console.Write("Count:" + count + ", for circle time:");
Console.WriteLine(timer.Elapsed.Ticks);
#endregion

#region linq
timer = new Stopwatch();
timer.Start();
int count2 = 0;
count2 = list1.Where(p => p.Id >= 1 && p.Id < 1000).Count();
timer.Stop();

Console.Write("Count:" + count2 + ", linq time:");
Console.WriteLine(timer.Elapsed.Ticks);
#endregion

#region delegate
timer = new Stopwatch();
timer.Start();
int count3 = list1.ToList().FindAll(delegate(TestClass post)
{
return post.Id >= 1 && post.Id < 1000;
}).Count;

timer.Stop();
Console.Write("Count:" + count3 + ", delegate time:");
Console.WriteLine(timer.Elapsed.Ticks);
#endregion

Console.Read();
}

而我得出的结论:



希望广大朋友指正,水平有限!!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: