gpt4 book ai didi

c# - LINQ vs foreach vs for性能测试结果

转载 作者:太空狗 更新时间:2023-10-29 18:13:17 27 4
gpt4 key购买 nike

有人可以解释这些结果吗?我知道有重复的问题,但我还没有找到一个与我的结果得出相同结论的问题 :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;
}
}
}
}
}

enter image description here

最佳答案

您永远不会执行 LINQ 查询,您只是创建它。您应该使用 ToListToArray 方法来强制迭代,可能您不会得到不同的结果,因为 LINQ 使用 foreach 循环也是如此。

编辑:LINQ 需要更多时间,因为您要遍历所有项目。但是在你的其他两个循环中,一旦找到匹配项,你就会打破循环。尝试使用 FirstOrDefault 而不是 Where,您应该会得到相同(或相似)的结果。

people.FirstOrDefault(p => p.Name == name);

关于c# - LINQ vs foreach vs for性能测试结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22851234/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com