什么是for循环的优化方式

问题描述 投票:-1回答:3

对于性能而言,For Loop更适合编码标准

var totalCount = new List<int>();
  1. 的foreach
 foreach(var student in StudentList)
 {
      var studentItem= student.DataContext as studentEntity;
      if (studentItem!= null)
      {
            totalCount.Add(studentItem.Id);
      }
 }                
  1. 的ForEach
StudentList?.ForEach(student=>
{
    var studentItem= student.DataContext as studentEntity;
    if (studentItem!= null)
    {
        totalCount.Add(studentItem.Id);
    }
});

我的问题是,在快速性能中哪个循环更正确。

如果在我的StudentList中有1000及以上的记录,我想在c#中执行逻辑操作,那么ForLoop对于Fast Perfomance更好

先感谢您 !!!

c# linq loops
3个回答
3
投票

让.Net为你做,摆脱任何循环:

https://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx

 totalCount.AddRange(studentList);

它更具可读性和(可能)更高效。

编辑:如果totalCountstudentList有不同的类型,添加Select,例如:

totalCount.AddRange(studentList.Select(student => student.Id));

0
投票

它们在优化方面几乎相同,你可以查看Eric Lippert's blog: “foreach” vs “ForEach”,在那里他谈到这个并在内部展示forEach。

public static void ForEach<T>(this IEnumerable<T> sequence, Action<T> action)
{ 
  // argument null checking omitted
  foreach(T item in sequence) action(item);
}

0
投票

另一个用于从另一个列表创建列表的.NET(LINQ)方法(一个班轮粉丝的单行)

var totalCount = studentList.ToList();

另一种LINQ方法,当你已经存在的项目时。

var totalCount = new List<int> { 1, 2 ,3 };

var all = totalCount.Concat(studentList).ToList();

不可能不坚持榜样,因为只有当你知道问题的背景时才能实现性能。

在您更新的示例中,可读且速度足够快的方法

 var totalCount = 
     StudentList.Select(student => student.DataContext as Entity)
                .Where(entity => entity != null)
                .Select(entity => entity.Id)
                .ToList();
© www.soinside.com 2019 - 2024. All rights reserved.