title: ActiveDirectory: Query Performance
body: <p>I'm trying to read all users from an Active Directory. However, this is rather slow (300 users take around 10 secs). Here's the code:</p>
  
  <pre><code>public void LoadADUsers()
  {
     using (var Context = new PrincipalContext(ContextType.Domain, "MyServer"))
     {
        using (var Searcher = new PrincipalSearcher(new UserPrincipal(Context)))
        {
           var DirectorySearcher = (DirectorySearcher)Searcher.GetUnderlyingSearcher();
           DirectorySearcher.PropertiesToLoad.Clear();
           DirectorySearcher.PropertiesToLoad.Add("cn");
           DirectorySearcher.PropertiesToLoad.Add("samAccountName");
  
           foreach (var Result in Searcher.FindAll())
           {
              var Entry = (DirectoryEntry)Result.GetUnderlyingObject();
              string FullName = (string)Entry.Properties["cn"].Value;
              string AccountName = (string)Entry.Properties["samAccountName"].Value;
              ADUsers.Add(new ADUser(Entry.Guid.ToString(), FullName, AccountName));
           }
        }
     }
  }
  </code></pre>
  
  <p>Now, the creation of the <code>Context</code> object takes around 7 secs, probably because this is where the connection to the server is established. Is there any way to speed this up?</p>
  
  <p>Additionally, the loop takes around 2.5 secs, probably meaning that there is still communication with the AD server going on. I expected that the <code>Searcher.FindAll()</code> call would receive all users at once, but that doesn't seem to be the case. Any way to enforce that behavior, or to otherwise speed up the loop?</p>