Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any faster way than .Any() to find if IEnumerable<T> has any data?

When running the profiler on my code I am showing a total execution time of 20 seconds, 14 seconds of this (14,788.4 ms) is being taken up by a call to IEnumerable.Any() is there any way to speed this up at all?

The table being pulled from has a total of ~484,000 records, so putting that in to memory would be best avoided.

I have tried Replacing IEnumerable.Any() with IEnumerable.Count() > 0 and using IEnumerable.GetEnumerator().MoveNext()

All of which provide no significant change in execution time.

IEnumerable<Registration> result = [Fill by Query] (19ms)
[Conditions] (<0.1ms for all)
[Tried all of the following with no performance impact]
return result != null && result.Any(); (14000ms)
return result != null && result.Count() > 0; (14000ms)
return result != null && result.GetEnumerator().MoveNext(); (14000ms)
return (result?.Any() ?? false); (14000ms)

I'm hoping that I can find something that will reduce the total execution time to a reasonable number, IEnumerable.Any() being the only bottleneck.

like image 592
Lady_A Avatar asked Dec 23 '22 23:12

Lady_A


1 Answers

You need to call Queryable.Any, not Enumerable.Any, so that the actual database query can be adjusted to only query whether or not any items exist. By turning the IQueryable into an IEnumerable you're ensuring that the operations you're performing on it all involve materializing the results of the query in memory before that operation can be performed.

like image 150
Servy Avatar answered Mar 01 '23 23:03

Servy