【发布时间】:2013-06-03 09:10:47
【问题描述】:
我正在测试从 Dictionary VS 列表中获取数据的速度。
我用这段代码测试过:
internal class Program
{
private static void Main(string[] args)
{
var stopwatch = new Stopwatch();
List<Grade> grades = Grade.GetData().ToList();
List<Student> students = Student.GetStudents().ToList();
stopwatch.Start();
foreach (Student student in students)
{
student.Grade = grades.Single(x => x.StudentId == student.Id).Value;
}
stopwatch.Stop();
Console.WriteLine("Using list {0}", stopwatch.Elapsed);
stopwatch.Reset();
students = Student.GetStudents().ToList();
stopwatch.Start();
Dictionary<Guid, string> dic = Grade.GetData().ToDictionary(x => x.StudentId, x => x.Value);
foreach (Student student in students)
{
student.Grade = dic[student.Id];
}
stopwatch.Stop();
Console.WriteLine("Using dictionary {0}", stopwatch.Elapsed);
Console.ReadKey();
}
}
public class GuidHelper
{
public static List<Guid> ListOfIds=new List<Guid>();
static GuidHelper()
{
for (int i = 0; i < 10000; i++)
{
ListOfIds.Add(Guid.NewGuid());
}
}
}
public class Grade
{
public Guid StudentId { get; set; }
public string Value { get; set; }
public static IEnumerable<Grade> GetData()
{
for (int i = 0; i < 10000; i++)
{
yield return new Grade
{
StudentId = GuidHelper.ListOfIds[i], Value = "Value " + i
};
}
}
}
public class Student
{
public Guid Id { get; set; }
public string Name { get; set; }
public string Grade { get; set; }
public static IEnumerable<Student> GetStudents()
{
for (int i = 0; i < 10000; i++)
{
yield return new Student
{
Id = GuidHelper.ListOfIds[i],
Name = "Name " + i
};
}
}
}
内存中有学生和成绩的列表,他们有共同的 StudentId。
在第一种方式中,我尝试在我的机器上花费近 7 秒的列表上使用 LINQ 查找学生的成绩,而在另一种方式中,我首先将 List 转换为字典,然后使用不到一秒的键从字典中查找学生的成绩。
【问题讨论】:
-
您是否尝试过相反的方法(先使用字典测试,然后再使用列表)?
-
@Fendy 是的。没有区别。
-
它被称为Shlemiel the painter's algorithm。答案解释了为什么会这样。
-
了解一些简单的数据结构确实有助于编程,所以我建议您阅读一些相关信息。
-
更合理的比较是字典(键)与列表(索引)。
标签: c# .net performance