我一直在对我构建的 REST API 中的性能进行故障排除,除其他外,它根据提供的搜索词从 Active Directory 中返回用户列表。根据我为测试目的而内置的一些日志记录,我可以看到获取设置(例如 LDAP 搜索信息)和检索所有搜索结果的整个过程不到一秒钟:
30/08/2017 3:37:58 PM | Getting search results.
30/08/2017 3:37:58 PM | Retrieving default settings
30/08/2017 3:37:58 PM | Default settings retrieved. Creating directoryEntry
30/08/2017 3:37:58 PM | Search retrieved.
30/08/2017 3:37:58 PM | Iterating through search results.
30/08/2017 3:38:16 PM | Search results iteration complete.
但是,正如您所见,遍历这些搜索结果并填充我的用户列表需要 18 秒。这是我的代码:
SearchResultCollection resultList = new DirectorySearcher(CreateDirectoryEntry())
{
Filter = ("(&(objectClass=user) (cn=*" + SearchTerm + "*))"),
PropertiesToLoad =
{
"givenName",
"sn",
"sAMAccountName",
"mail"
}
}.FindAll();
foreach (SearchResult result in resultList)
{
ADUser thisUser = new ADUser();
try
{
thisUser.Firstname = result.Properties["givenName"][0].ToString();
}
catch
{
thisUser.Firstname = "Firstname not found";
}
try
{
thisUser.Lastname = result.Properties["sn"][0].ToString();
}
catch
{
thisUser.Lastname = "Lastname not found";
}
try
{
thisUser.EmailAddress = result.Properties["mail"][0].ToString();
}
catch
{
thisUser.EmailAddress = "Email address not found";
}
UserList.Add(thisUser);
}
这很香草,没有做任何花哨的事情。知道为什么这会这么慢,或者有什么建议我可以做些什么来加快速度吗?
更新
根据评论和答案,我从代码中删除了 null 检查。所以现在它看起来像这样:
foreach (SearchResult result in resultList)
{
ADUser thisUser = new ADUser();
thisUser.Firstname = result.Properties["givenName"][0].ToString();
thisUser.Lastname = result.Properties["sn"][0].ToString();
thisUser.EmailAddress = result.Properties["mail"][0].ToString();
UserList.Add(thisUser);
}
这并没有提高性能。我可以看到这个循环仍然需要大约 18 秒,即使只返回一个结果。(这也证明了我的广告中糟糕的数据意味着我需要这个空检查!)