LINQ vs foreach vs 性能测试结果 [英] LINQ vs foreach vs for performance test results
问题描述
有人可以解释这些结果吗?我知道有重复的问题,但我还没有找到一个与我的结果得出相同结论的问题:o
Could somebody explain these results? I know there are duplicate questions, but I have yet to find a single question that came to the same conclusion as my results :o
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SpeedTest
{
class Person
{
public Person(string name)
{
this.Name = name;
}
public string Name { get; set; }
}
class Program
{
static void Main(string[] args)
{
var people = new List<Person>();
AddTwins("FRANCISCO", people);
var stopwatch = new Stopwatch();
string name = "OCSICNARF";
long linqTime = 0L;
long foreachTime = 0L;
long forTime = 0L;
stopwatch.Start();
Person person0;
var result = from person in people
where person.Name == name
select person;
person0 = result.First();
linqTime = stopwatch.ElapsedMilliseconds;
stopwatch.Restart();
Person person1;
foreach (Person p in people)
{
if (p.Name == name)
{
person1 = p;
break;
}
}
foreachTime = stopwatch.ElapsedMilliseconds;
stopwatch.Restart();
Person person2;
for (int i = 0; i < people.Count; i++)
{
if (people[i].Name == name)
{
person2 = people[i];
break;
}
}
forTime = stopwatch.ElapsedMilliseconds;
stopwatch.Stop();
Console.WriteLine(string.Format("LINQ took {0}ms", linqTime));
Console.WriteLine(string.Format("FOREACH took {0}ms", foreachTime));
Console.WriteLine(string.Format("FOR took {0}ms", forTime));
}
static void AddTwins(string name, List<Person> people)
{
AddTwins(people, name, "");
}
private static void AddTwins(List<Person> people, string choices, string chosen)
{
if (choices.Length == 0)
{
people.Add(new Person(chosen));
}
else
{
for (int i = 0; i < choices.Length; i++)
{
// choose
char c = choices[i];
string choose1 = choices.Substring(0, i);
string choose2 = choices.Substring(i + 1);
choices = choose1 + choose2;
// explore
AddTwins(people, choices, chosen + c);
// Unchoose
string unchoose1 = choices.Substring(0, i);
string unchoose2 = choices.Substring(i);
choices = unchoose1 + c + unchoose2;
}
}
}
}
}
推荐答案
您从不执行 LINQ
查询,您只需创建它.你应该使用 ToList
或 ToArray
方法来强制迭代,可能你不会得到不同的结果,因为 LINQ
使用了 foreach
循环也是如此.
You never execute the LINQ
query, you just create it. You should use ToList
or ToArray
method to force an iteration, probably you won't get a different result because LINQ
uses a foreach
loop as well.
编辑:LINQ
需要更多时间,因为您要迭代所有项目.但是在其他两个循环中,一旦找到匹配项,就会打破循环.尝试使用 FirstOrDefault
而不是 Where
,你应该得到相同(或相似)的结果.
Edit: LINQ
takes a little bit more time because you are iterating over all of the items. But in your other two loops you are breaking the loop as soon as you find a match. Try using FirstOrDefault
instead of Where
and you should get the same (or similar) result.
people.FirstOrDefault(p => p.Name == name);
这篇关于LINQ vs foreach vs 性能测试结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!