我写了一个帮助程序类来获取域中的所有计算机,但它有点慢。虽然返回了128个对象,但我还是想加快速度。有什么想法吗?
public class DomainBrowser
{
private const string Computer = "computer";
public string Domain { get; private set; }
public DomainBrowser(string domain)
{
this.Domain = domain.ToLower();
}
/// <summary>
/// This method returns a list of the computer names available in the current domain.
/// </summary>
/// <returns></returns>
public List<string> GetComputers()
{
var winDirEntries = new DirectoryEntry("WinNT:");
var computers = (from DirectoryEntry domain in winDirEntries.Children
where domain.Name.ToLower() == this.Domain
from DirectoryEntry pc in domain.Children
where pc.SchemaClassName.ToLower().Contains(Computer)
select pc.Name).ToList();
return computers;
}
}
答案 0 :(得分:2)
这里最大的问题之一是所有ToLower()
次来电。字符串是不可变的,因此每次更改它们(例如将它们更改为小写,如代码示例中所示)都会创建一个新对象。另外,小写字符串所涉及的逻辑比你想象的要贵,因为它必须考虑当前文化设置之类的东西。
为了降低费用,请尝试不要更改字符串引用,而是将它们与不区分大小写进行比较:
var computers = (from DirectoryEntry domain in winDirEntries.Children
where string.Equals(domain.Name, this.Domain, StringComparison.OrdinalIgnoreCase)
from DirectoryEntry pc in domain.Children
where pc.SchemaClassName.IndexOf(Computer, StringComparison.OrdinalIgnoreCase) != -1
select pc.Name).ToList();
请注意,我必须将string.Compare
更改为string.IndexOf
,因为Compare
没有符合大小写不敏感的重载。