检查列表中未包含在另一个列表中的值的最佳方法。 (性能测试)

时间:2017-06-21 18:11:18

标签: c# performance loops lambda foreach

我正在各种方法之间执行一些性能测试,以检查哪些对象在一个列表中,而不是在另一个列表中。 我想出了一个我没想到的结果,使用lambda执行相同操作的平均时间是while,for,foreach和lambda之间的最高时间。

使用的代码:

// Object
public class ComplexObject
{
    public int Number { get; set; }
    public char Character { get; set; }
}

// Lists
private readonly List<ComplexObject> _complexList1 = new List<ComplexObject>();
private readonly List<ComplexObject> _complexList2 = new List<ComplexObject>();

/* Fills in lists with numbers from 0 to 100000 and characters from 0 to 50.
 * The first list contains 10000 records and a second list contains 1000 records. */
private void FillLists()
{
    var rnd = new Random();
    for (int i = 0; i < 100000; i++)
    {
        _complexList1.Add(new ComplexObject
        {
            Number = rnd.Next(5000),
            Character = (char)rnd.Next(50)
        });
    }
    for (int i = 0; i < 1000; i++)
    {
        _complexList2.Add(new ComplexObject
        {
            Number = rnd.Next(5000),
            Character = (char)rnd.Next(50)
        });
    }
}

// For
public void ExecuteFor()
{
    var result = new List<ComplexObject>();
    for (int countList2 = 0; countList2 < _complexList2.Count; countList2++)
    {
        bool found = false;
        for (int countList1 = 0; countList1 < _complexList1.Count; countList1++)
        {
            if (_complexList2[countList2].Number == _complexList1[countList1].Number &&
                _complexList2[countList2].Character == _complexList1[countList1].Character)
            {
                found = true;
                break;
            }
        }

        if (!found)
            result.Add(_complexList2[countList2]);
    }
}

// Foreach
public void ExecuteForeach()
{
    var result = new List<ComplexObject>();
    foreach (ComplexObject object2 in _complexList2)
    {
        bool found = false;
        foreach (ComplexObject object1 in _complexList1)
        {
            if (object2.Number == object1.Number &&
                object2.Character == object1.Character)
            {
                found = true;
                break;
            }
        }

        if (!found)
            result.Add(object2);
    }
}

// Lambda
public void ExecuteLambda()
{
    var result =
        _complexList2.Count(
            l2 => _complexList1.All(l1 => l2.Number != l1.Number || l2.Character != l1.Character));
}

使用StopWatch测量时间并运行每个循环类型10次并取平均执行时间,结果如下:

For: 10.163.836 在avarage中打勾 Foreach: 8.747.627 平均值 Lambda: 14.326.094 在avarage中打勾

问题是:
还有其他方法可以解决我的问题吗? Lambda真的比普通的循环花费更多的时间吗?

2 个答案:

答案 0 :(得分:1)

您可以尝试使用Except扩展方法,该方法将返回两个序列的列表项差异:

List<ComplexObjects> _onlyInList1 = _complexList1.Except(_complexList2);

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

答案 1 :(得分:0)

  

Lambda真的比普通循环花费更多时间吗?

看看here,看看为什么通常会这样 并here看到一些异常。