MartinH
MartinH

Reputation: 1490

Performance recursive lookup function C#

We have the following recursive function which is used for looking up the member objects, which are listed in the following property of the group object. We use the group list for the recursive check in the groups.

This function with approximately 30k users and 40k groups takes about 20 minutes to run, which we want to speed up. Any ideas how to do this more efficient?

foreach (ad_group_source group in group_source)
{
    List<ad_user_source> list = FindMembers(group, group_source, user_source);
}

public static List<ad_user_source> FindMembers(ad_group_source group, HashSet<ad_group_source> group_source, HashSet<ad_user_source> user_source)
{
    List<String> members = group.Members.Split(';').ToList();
    if (members.Equals(""))
    {
        return new List<ad_user_source>();
    }
    List<ad_user_source> members2 = new List<ad_user_source>();
    foreach (String member in members)
    {
        if (!member.Equals(""))
        {
            Boolean isUser = false;
            ad_user_source gebruiker = user_source.FirstOrDefault(u => u.DistinguishedName == member);
            if (gebruiker != null)
            {
                members2.Add(gebruiker);
                isUser = true;
            }
            if (!isUser)
            {
                ad_group_source group2 = group_source.FirstOrDefault(g => g.CN == member.Substring(3));
                if (group2 != null)
                {
                    List<ad_user_source> l = FindMembers(group2, group_source, user_source);
                    members2.AddRange(l);
                }
            }
         }

     }
     List<ad_user_source> members3 = members2.Distinct().ToList();
     return members3;
 }

Upvotes: 0

Views: 159

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 727137

The problem is that your code keeps using hash sets as if they were lists. This is very inefficient.

To address this problem construct a Dictionary<string,ad_user_source> organized by DistinguishedName, and Dictionary<string,ad_group_source> organized by g.CN. Don't put groups with CN that is longer than three characters, in case there are any in the original set.

Upvotes: 2

Related Questions