为什么使用PrincipalSearcher比FindByIdentity()更快?

sha*_*oth 14 .net c# security azure windows-server-2008

我有这个代码:

var context = new PrincipalContext( ContextType.Machine );
var user = UserPrincipal.FindByIdentity( context, username );
Run Code Online (Sandbox Code Playgroud)

运行大约需要2-3秒.我被建议用PrincipalSearcherclass 重写它:

var context = new PrincipalContext( ContextType.Machine );
var user = new UserPrincipal(context);
user.SamAccountName = username;
var searcher = new PrincipalSearcher(user);
user = searcher.FindOne() as UserPrincipal;
Run Code Online (Sandbox Code Playgroud)

它在不到一秒的时间内运行 - 特别快.建议重写的人为什么和我一样无能为力.

为什么它会产生任何性能差异?

mar*_*c_s 5

我能想到的唯一可信的原因是.FindByIdentity必须检查匹配的多个属性,因为您没有准确指定您正在寻找的属性.

你可以通过指定你正在寻找的属性(使用这个方法重载)来做到这一点 - 尝试这个比较:

var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);
Run Code Online (Sandbox Code Playgroud)

这有多快?

  • 有趣的是,使用三个参数的代码`FindByIdentity()`的工作速度比原始的`FindByIdentity()`慢一点. (3认同)