Question

I wrote a helper class to get all computers on a domain, but it's a tad bit slow. While there are 128 objects returned, I'd still like to speed it up. Any ideas?

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;
    }
}
Was it helpful?

Solution

One of the biggest issues here is all of the ToLower() calls. Strings are immutable, so each change of them (such as changing them to lowercase as seen in your code sample) creates a new object. Additionally, the logic involved in lowercasing a string is more expensive than you might think, because it has to account for things like the current culture settings.

To mitigate the expense, try not altering the string references, instead comparing them with case insensitivity:

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();

Note that I had to change string.Compare to string.IndexOf because Compare does not have an overload that works with case insensitivity.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top