首先执行两个等效的LINQ查询总是运行较慢



请考虑以下两种写作linq查询的方法:

选项1:

public void MyMethod(List<MyObject> myList)
{
   ...
   var isValid = myList.Where(l => l.IsActive)
                       .GroupBy(l => l.Category)
                       .Select(g => g.Count() > 300) //arbitrary number for the sake of argument
                       .Any();
}

选项2:

public void MyMethod(List<MyObject> myList)
{
   ...
   var isValid = myList.Where(l => l.IsActive)
                       .GroupBy(l => l.Category)
                       .Select(g => g.Count()) 
                       .Any(total => total > 300); //arbitrary number for the sake of argument
}

我想看看两者之间的性能是否有任何差异,因此我创建了一个控制台应用程序(如下所示)来比较它们。

发生的事情是,首先执行的查询总是较慢,然后在随后的运行中它们都以0毫秒为单位显示。然后,我将比较值更改为tick,并获得了相似的结果。如果我切换执行查询的顺序,则新的第一个运行速度较慢。

所以问题是双重的,为什么第一个执行的查询似乎是较慢的问题?而且,有没有一种方法可以实际比较两者的性能?

这是测试代码:

static void Main(string[] args)
{
    Console.WriteLine("Running test");
    var rnd = new Random();
    for (var i = 0;i < 5; i++)
    {
        RunTest(i, rnd);
        Console.WriteLine();
        Console.WriteLine();
    }
    Console.ReadKey();
}
private static void RunTest(int runId, Random rnd)
{
    var list = GetData(rnd);
    var startOne = DateTime.Now.TimeOfDay;
    var one = list.Where(l => l.IsActive)
        .GroupBy(l => l.Category)
        .Select(g => g.Count() > 300)
        .Any();
    var endOne = DateTime.Now.TimeOfDay;
    var startTwo = DateTime.Now.TimeOfDay;
    var two = list.Where(l => l.IsActive)
        .GroupBy(l => l.Category)
        .Select(g => g.Count())
        .Any(c => c > 300);
    var endTwo = DateTime.Now.TimeOfDay;
    var resultOne = (endOne - startOne).Milliseconds;
    var resultTwo = (endTwo - startTwo).Milliseconds;
    Console.WriteLine($"Results for test run #{++runId}");
    Console.WriteLine();
    Console.WriteLine($"Category 1 total: {list.Where(l => l.Category == 1 && l.IsActive).Count()}");
    Console.WriteLine($"Category 2 total: {list.Where(l => l.Category == 2 && l.IsActive).Count()}");
    Console.WriteLine($"Category 3 total: {list.Where(l => l.Category == 3 && l.IsActive).Count()}");
    Console.WriteLine();
    Console.WriteLine($"First option runs in: {resultOne} ");
    Console.WriteLine();
    Console.WriteLine($"Second option runs in: {resultTwo} ");
}
    private static List<MyObject> GetData(Random rnd)
    {
        var result = new List<MyObject>();
        for (var i = 0; i < 1000; i++)
        {                
            result.Add(new MyObject { Category = rnd.Next(1, 4), IsActive = rnd.Next(0, 2) != 0 });
        }
        return result;
    }
}
    public class MyObject
    {
        public bool IsActive { get; set; }
        public int Category { get; set; }
    }

是的,您可以使用BenchmarkDotnet准确地比较两个选项的性能。这成为一个简单的测试脚本。

void Main()
{
    var summary = BenchmarkRunner.Run<CollectionBenchmark>();
}
[MemoryDiagnoser]
public class CollectionBenchmark
{
    private static Random random = new Random();
    private List<MyObject> _list = new List<MyObject>();
    [GlobalSetup]
    public void GlobalSetup()
    {
        var rnd = new Random();
        for (var i = 0; i < 1000; i++)
        {
            _list.Add(new MyObject { Category = rnd.Next(1, 4), IsActive = rnd.Next(0, 2) != 0 });
        }
    }
    [Benchmark]
    public void OptionOne()
    {
        var one = _list.Where(l => l.IsActive)
            .GroupBy(l => l.Category)
            .Select(g => g.Count() > 300)
            .Any();
    }
    [Benchmark]
    public void OptionTwo()
    {
        var two = _list.Where(l => l.IsActive)
            .GroupBy(l => l.Category)
            .Select(g => g.Count())
            .Any(c => c > 300);
    }
}
public class MyObject
{
    public bool IsActive { get; set; }
    public int Category { get; set; }
}

这在我的机器上产生以下结果:

BenchmarkDotNet=v0.10.14, OS=Windows 10.0.17134
Intel Core i5-6300U CPU 2.40GHz (Skylake), 1 CPU, 4 logical and 2 physical cores
Frequency=2437498 Hz, Resolution=410.2567 ns, Timer=TSC
  [Host]     : .NET Framework 4.6.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3324.0
  DefaultJob : .NET Framework 4.6.2 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.3324.0

|    Method |     Mean |     Error |    StdDev |  Gen 0 | Allocated |
|---------- |---------:|----------:|----------:|-------:|----------:|
| OptionOne | 36.73 us | 0.7491 us | 1.9202 us | 8.4839 |  13.13 KB |
| OptionTwo | 36.37 us | 0.6993 us | 0.8053 us | 8.4839 |  13.13 KB |

分配的内存是相同的。考虑到基准测量微秒的一部分时间的时间差,性能没有实际差异。

您的基准测试方法有几个问题。

首先,当您有两个DateTime值时,您可以通过其TimeOfDay属性进行比较...

var startOne = DateTime.Now.TimeOfDay;
// Do some work
var endOne = DateTime.Now.TimeOfDay;
var resultOne = (endOne - startOne).Milliseconds;

...然后,如果测试每天过渡(午夜),则有可能获得持续时间的风险。考虑一下...

DateTime midnight = DateTime.Today;
DateTime fiveSecondsBeforeMidnight = midnight - TimeSpan.FromSeconds(5);
DateTime fiveSecondsAfterMidnight  = midnight + TimeSpan.FromSeconds(5);
Console.WriteLine($"Difference between DateTime  values: {fiveSecondsAfterMidnight - fiveSecondsBeforeMidnight}");
Console.WriteLine($"Difference between TimeOfDay values: {fiveSecondsAfterMidnight.TimeOfDay - fiveSecondsBeforeMidnight.TimeOfDay}");

...哪个印刷...

Difference between DateTime  values: 00:00:10
Difference between TimeOfDay values: -23:59:50

相反,您可以通过直接比较DateTime值来修复此错误并简化代码...

var startOne = DateTime.Now;
// Do some work
var endOne = DateTime.Now;
var resultOne = (endOne - startOne).Milliseconds;

但是,通过使用Stopwatch类可以进一步改进,这比比较DateTime值更准确,并专门为此目的设计...

Stopwatch stopwatch = Stopwatch.StartNew();
// Do some work
TimeSpan resultOne = stopwatch.Elapsed;
stopwatch.Restart();
// Do some work
TimeSpan resultTwo = stopwatch.Elapsed;

第二,TimeSpan.Milliseconds属性仅返回TimeSpan值的毫秒组件。要在毫秒中获取TimeSpan,您需要TotalMilliseconds属性。考虑这里的区别...

TimeSpan value1 = TimeSpan.FromSeconds(1) + TimeSpan.FromMilliseconds(500);
TimeSpan value2 = TimeSpan.FromMilliseconds(900);
Console.WriteLine($"     value1.Milliseconds: {value1.Milliseconds}");
Console.WriteLine($"value1.TotalMilliseconds: {value1.TotalMilliseconds}");
Console.WriteLine($"     value2.Milliseconds: {value2.Milliseconds}");
Console.WriteLine($"value2.TotalMilliseconds: {value2.TotalMilliseconds}");
Console.WriteLine($"value1 is {(value1.Milliseconds      < value2.Milliseconds      ? "less" : "greater")} than value2 (by Milliseconds)");
Console.WriteLine($"value1 is {(value1.TotalMilliseconds < value2.TotalMilliseconds ? "less" : "greater")} than value2 (by TotalMilliseconds)");

...哪个印刷...

     value1.Milliseconds: 500
value1.TotalMilliseconds: 1500
     value2.Milliseconds: 900
value2.TotalMilliseconds: 900
value1 is less than value2 (by Milliseconds)
value1 is greater than value2 (by TotalMilliseconds)

像您一样,比较Ticks属性将是另一种解决方案,或者您可以将时间差作为TimeSpan存储而无需摘下其属性之一,然后让字符串格式化较小的组件...

TimeSpan resultOne = endOne - startOne;
TimeSpan resultTwo = endTwo - startTwo;
// ...
Console.WriteLine($"First option runs in: {resultOne:s\.ffffff} seconds");
Console.WriteLine();
Console.WriteLine($"Second option runs in: {resultTwo:s\.ffffff} seconds");

最后,我运行了您的代码,并看到了相同的结果:第一批运行是非零的,随后的运行为零。我的猜测是,由于您的代码尚未得到优化,因此第一个运行需要更长的时间。即使是那些"慢"的第一次运行,只需完成毫秒即可完成的问题,因为您的列表只有一千个项目。基准运行的简短不提供有意义的比较。

进行上述更改并增加了GetData()返回的List<>的大小增加到1000万个项目,每次运行需要几秒钟,第一个选项是在第一次运行中更快几毫秒,随后的速度在随后的25-125毫秒内慢25-125毫秒。运行。

您可以考虑使用诸如BenchmarkDotnet之类的库,而不是滚动自己的基准代码。它处理详细信息,例如弄清楚要执行多少次运行,"加热"您的代码以确保已得到优化,并为您计算统计信息。

相关内容

  • 没有找到相关文章

最新更新