2

I have an array of structs and I need to locate all the elements that share a certain condition.

Currently I use:

Array.FindAll(someArray, x => x.eg == "*Perfomance Test*")

But after some googling I noticed that there is a much faster way by using the LINQ Where-method.

someArray.Where(x => x.eg == "*Perfomance Test*")

I did some testing and the results are pretty impressive:

  • FindAll: 00:00:03.06
  • Where: 00:00:00.20

The problem is that Where returns IEnumerable. And I call this method that returns all these certain elements from the array within the for loop. Which is the type of loop I need to use. I used the .ToArray() method, but that made it much worse so that FindAll() is the faster approach.

Because of that it seems to me that if I need to get an array of elements, Where is much slower option than FindAll. But maybe I'm missing something.

Are there any better, faster options?

Marcus Wichelmann
  • 762
  • 1
  • 6
  • 18
UnknownUser
  • 327
  • 2
  • 14
  • 2
    Well, try `Where(...).ToArray()` and you'll be surprised. – 41686d6564 stands w. Palestine Aug 31 '19 at 19:35
  • 1
    `Where` appears to be faster on first sight because it uses deferred execution. It doesn't actually go and find the elements until you called `ToArray`. – Sweeper Aug 31 '19 at 19:35
  • Yeah but after I used .ToArray() performance wise is much worse. Slower than calling FindAll(). FindAll: 00:00:02.92 and Where: 00:00:03.07 – UnknownUser Aug 31 '19 at 19:37
  • @UnknownUser Yes, that's because `Where` on its own only builds the query; it doesn't actually do the search until you "request" that (using something like `ToArray(), `ToList()`, `FirstOrDefault()`, etc.) – 41686d6564 stands w. Palestine Aug 31 '19 at 19:38
  • Now I understand, but are there any better search options? Faster than FindAll or Where().ToArray(). I call this method quite frequently and I'm worried that this might get an impact on performance. – UnknownUser Aug 31 '19 at 19:40
  • 2
    Well, if you look at the [source code](https://referencesource.microsoft.com/#mscorlib/system/array.cs,1111) of `FindAll()`, it simply just uses a for loop internally and checks each element against the given condition; that's all. So, I don't really think you can beat that. – 41686d6564 stands w. Palestine Aug 31 '19 at 19:43
  • The linked duplicates are, strictly speaking, about `List.FindAll()` rather than `Array.FindAll()` but the same answers apply. – dbc Aug 31 '19 at 20:03

0 Answers0