HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpMinor

Is this Recursion + Linq example inefficient?

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
thislinqrecursionexampleinefficient

Problem

I have a hierarchy of of groups, and I want to get a collection of all the lowest level groups (or leaves if we'll look at this as a tree).

I wrote the following code. Is it inefficient?

public static class FeatureWeightGroupExtensions
{
    public static IEnumerable GetLeafGroups(this IFeatureWeightGroup featureWeightGroup)
    {
        return GetLeafGroupsRecursive(featureWeightGroup).ToList();
    }

    private static IEnumerable GetLeafGroupsRecursive(IFeatureWeightGroup featureWeightGroup)
    {
        if (!featureWeightGroup.ChildGroups.Any())
            return Enumerable.Repeat(featureWeightGroup, 1);

        return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty(),
                                                        (allGroups, group) =>
                                                        allGroups.Concat(GetLeafGroupsRecursive(group)));
    }
}

Solution

return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty(),
                                                    (allGroups, group) =>
                                                    allGroups.Concat(GetLeafGroupsRecursive(group)));


It looks like it can be replaced with:

return featureWeightGroup.ChildGroups
           .SelectMany(g => GetLeafGroupsRecursive(group));


Which probably will not be much better from performance point of view, but looks cleaner.

Code Snippets

return featureWeightGroup.ChildGroups.Aggregate(Enumerable.Empty<IFeatureWeightGroup>(),
                                                    (allGroups, group) =>
                                                    allGroups.Concat(GetLeafGroupsRecursive(group)));
return featureWeightGroup.ChildGroups
           .SelectMany(g => GetLeafGroupsRecursive(group));

Context

StackExchange Code Review Q#966, answer score: 5

Revisions (0)

No revisions yet.