LINQ performance Count vs Where and Count

前端 未结 6 2019
礼貌的吻别
礼貌的吻别 2020-12-08 10:14
public class Group
{
   public string Name { get; set; }
}  

Test:

List _groups = new List();

for (i         


        
6条回答
  •  孤街浪徒
    2020-12-08 10:50

    Sarge Borsch gave the proper answer in the comments but without further explanations.

    The problems lies with the fact that the bytecode must be compiled to x86 by the JIT compiler on the first run. As a result your measure incorporates both what you wanted to test and the compilation time. And since most of the things used by the second test will have been compiled during the first test (the list enumerator, the Name property getter, etc), the first one is more impacted by the compilation.

    The solution is to do a "warm-up": you run your code once without doing measures, usually with just one iteration, simply to have it compiled. Then you start the stopwatch and run it again for real, with as many iterations as needed to get a long enough duration (one second for example).

提交回复
热议问题