2

我写了一个帮助类来获取域中的所有计算机,但它有点慢。虽然返回了 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;
    }
}
4

1 回答 1

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没有不区分大小写的重载。

于 2013-06-26T20:22:56.350 回答