我需要获取活动目录记录并插入SQL数据库中。大约有10,000条记录。我使用了这个代码:
List<ADUser> users = new List<ADUser>();
DirectoryEntry entry = new DirectoryEntry("LDAP://xyz.com");
ADUser userToAdd = null;
IList<string> dict = new List<string>();
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(&(objectClass=user))";
search.PropertiesToLoad.Add("samaccountname");
search.PageSize = 1000;
foreach (SearchResult result in search.FindAll())
{
DirectoryEntry user = result.GetDirectoryEntry();
if (user != null && user.Properties["displayName"].Value!=null)
{
userToAdd = new ADUser
{
FullName = Convert.ToString(user.Properties["displayName"].Value),
LanId = Convert.ToString(user.Properties["sAMAccountName"].Value)
};
users.Add(userToAdd);
}
}如何从速度和空间复杂度的角度优化上述代码?是否可以使用二叉树中的遍历,因为结构看起来类似于二叉树。
发布于 2018-11-26 18:09:21
DirectorySearcher.FindAll()返回的列表只是一个列表。所以你不能比你现在更好地穿越它。
要优化这一点,不要使用GetDirectoryEntry()。这是在做两件事:
DirectoryEntry对象都将留在内存中,直到调用Dispose()或GC有时间运行为止(直到循环结束,它才会运行)。首先,将displayName添加到PropertiesToLoad中以确保返回。然后可以使用result.Properties[propertyName][0]访问每个属性。使用这种方法,每个属性都作为数组返回,即使它是AD中的单个值属性,因此您需要[0]。
另外,如果您的应用程序在此搜索完成后仍处于打开状态,请确保您在Dispose()上调用了从FindAll()中提取出来的SearchResultCollection。在FindAll()的文档中,“备注”部分表示如果不这样做,可能会有内存泄漏。或者,您可以将它放在using块中:
DirectorySearcher search = new DirectorySearcher(entry);
search.Filter = "(&(objectClass=user))";
search.PropertiesToLoad.Add("sAMAccountName");
search.PropertiesToLoad.Add("displayName");
search.PageSize = 1000;
using (SearchResultCollection results = search.FindAll()) {
foreach (SearchResult result in results) {
if (result.Properties["displayName"][0] != null) {
userToAdd = new ADUser {
FullName = (string) result.Properties["displayName"][0],
LanId = (string) result.Properties["sAMAccountName"][0]
};
users.Add(userToAdd);
}
}
}https://stackoverflow.com/questions/53486150
复制相似问题