我可以加快此查询的速度以检索域上的所有计算机吗
本文关键字:计算机 检索 查询 速度 我可以 | 更新日期: 2023-09-27 18:20:06
我写了一个助手类来获取域上的所有计算机,但它有点慢。虽然返回了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;
}
}
这里最大的问题之一是所有的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
没有使用不区分大小写的重载。