【问题标题】:How would I be able to Optimize my Function我将如何优化我的功能
【发布时间】:2016-01-28 20:31:46
【问题描述】:

我有这个 JsonResult 搜索活动目录中的所有用户并将特定用户添加到列表中。然而,由于有很多员工,搜索需要一些时间。

这是json结果:

public JsonResult Search(string term)
{
    List<string> lstADUsers = new List<string>();       
    if (!string.IsNullOrEmpty(term))
    {
        using (var context = new PrincipalContext(ContextType.Domain, null, "LDAP"))
        {   
            UserPrincipal user = new UserPrincipal(context);
            using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
            {                  
                foreach (var result in searcher.FindAll().Where(m => m.SamAccountName.StartsWith(term, StringComparison.OrdinalIgnoreCase)))
                {
                    DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;                     
                    string usersWithName;
                    if (!String.IsNullOrEmpty((String)de.Properties["samaccountname"].Value) && !String.IsNullOrEmpty((String)de.Properties["sn"].Value) && !String.IsNullOrEmpty((String)de.Properties["givenName"].Value))
                    {
                        usersWithName = de.Properties["samaccountname"].Value.ToString();
                        lstADUsers.Add(usersWithName);
                    }
                }
            }
        }
    }

    return Json(lstADUsers, JsonRequestBehavior.AllowGet);
}

现在它会搜索直到找到以用户输入的内容开头的内容:

如果我正在寻找 Jane.Doe,我输入了; Ja,它向我显示了活动目录中以 Ja 开头的所有用户的列表。如果没有超过10000名员工,它现在的运行方式会很好。您可以告诉搜索可能需要几秒钟才能将所有用户都添加到列表中。

您是否可以看到任何看起来可以优化的东西?

【问题讨论】:

  • 为什么不在第一次运行时全部缓存,然后只从匹配的列表中抓取?似乎这比一遍又一遍地查询要高效得多。
  • 对于性能检查,始终建议使用分析器确定热点。 Visual Studio 有一个非常好的性能和内存分析器。

标签: c# asp.net-mvc asp.net-mvc-4 optimization active-directory


【解决方案1】:

根据FindAll 执行实际调用(我相信这需要大部分时间),然后才应用过滤器。

更好的解决方案是在调用 FindAll 方法之前应用过滤器以减少返回的数据量。您可以使用 QueryFilter 属性来实现这一点。您可以找到使用示例in this thread

【讨论】:

    猜你喜欢
    • 2023-03-27
    • 2021-01-31
    • 2019-08-10
    • 1970-01-01
    • 1970-01-01
    • 2021-10-28
    • 2017-02-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多