basyura's blog

あしたになったらほんきだす。

FindAll と Where

class Class1 {
  static void Main(string[] args) {
    List<string> list = new List<string>()
    {
      "a","ab","c","d","af"
    };

    Stopwatch watch = new Stopwatch();
    watch.Start();
    List<string> extracted = list.FindAll((v)=> v.StartsWith("a"));
    watch.Stop();
    Console.WriteLine(watch.Elapsed.Milliseconds);
    // => 38

    foreach (string v in extracted)
    {
      Console.WriteLine(v);
    }

    Console.WriteLine("--------------------------------");

    watch.Restart();
    List<string> extracted2 = list.Where((v)=> v.StartsWith("a")).ToList();
    watch.Stop();
    Console.WriteLine(watch.Elapsed.Milliseconds);
    // => 1

    foreach (string v in extracted2)
    {
      Console.WriteLine(v);
    }
  }
}

FindAll の方が早いと思ったのに、Where の方が早い。なぜだ??