Search code examples
asp.netperformanceforeachldapldap-query

Iterating over SearchResultCollection is Very Slow


I'm running an LDAP query that returns multiple entries and stores them inside a SearchResultCollection. I'm iterating over the SearchResultCollection like so:

// results is my SearchResultCollection object
foreach (SearchResult sr in results)  
{
    ... do things to each SearchResult in here ...
}

This seems like the most logical way to do this, but loop is incredibly slow. When I step through the loop with the debugger, I find that it's the very first step of initializing the foreach loop that takes the time - the actual iterations are instantaneous.

In addition, when I view the contents of the SearchResultCollection while debugging, the watch takes just as long to load the contents of the variable.

I have a theory that the SearchResultCollection doesn't actually contain complete SearchResult objects, but rather references to entries in the Active Directory server that are then individually fetched when I iterate over the SearchResultCollection object. Can anyone confirm this theory? And is there a better (faster) way to fetch a set of LDAP entries?


Solution

  • There may be some ways to decrease the response time:

    • restrict the scope of the search
    • use a more restrictive search filter
    • use a base object closer to the object(s) being retrieved.

    see also