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

C# 为什么使用PrincipalSearcher比FindByIdentity()更快?,c#,.net,security,azure,windows-server-2008,C#,.net,Security,Azure,Windows Server 2008,我有这个密码: var context = new PrincipalContext( ContextType.Machine ); var user = UserPrincipal.FindByIdentity( context, username ); 运行大约需要2-3秒。有人建议我使用PrincipalSearcherclass: var context = new PrincipalContext( ContextType.Machine ); var user = new User

我有这个密码:

var context = new PrincipalContext( ContextType.Machine );
var user = UserPrincipal.FindByIdentity( context, username );
运行大约需要2-3秒。有人建议我使用
PrincipalSearcher
class:

var context = new PrincipalContext( ContextType.Machine );
var user = new UserPrincipal(context);
user.SamAccountName = username;
var searcher = new PrincipalSearcher(user);
user = searcher.FindOne() as UserPrincipal;
而且它的运行时间不到一秒钟——明显更快。建议重写的人和我一样不知道为什么它运行得更快


为什么它会造成性能差异?

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

可以通过指定要查找的属性()来完成此操作-请尝试以下方法进行比较:

var user = UserPrincipal.FindByIdentity(context, IdentityType.SamAccountName, username);

这有多快?

有趣的是,使用三个参数的代码
FindByIdentity()
比原来的
FindByIdentity()
慢一点。可能是算法实现的差异?